I seem to be getting application crashes at:
parent.findViewById(R.id.a_1).setVisibility(View.VISIBLE);
not sure what im doing wrong
code is below
layouttext.java
public class layouttest extends Activity {
private Spinner solvefor;
private ArrayAdapter<CharSequence> featuresAdapter;
private List<CharSequence> featuresList;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
featuresList = new ArrayList<CharSequence>();
featuresAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, featuresList);
featuresAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
solvefor = ((Spinner) layouttest.this.findViewById(R.id.solvefor));
solvefor.setAdapter(featuresAdapter);
featuresAdapter.add("Velocity");
featuresAdapter.add("Time");
featuresAdapter.add("Distance");
solvefor.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
}
MyOnItemSelectedListener.java package android.example.layouttest;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class MyOnItemSelectedListener implements OnItemSelectedListener {
private static final int SPINNER_OPTION_FIRST = 0;
private static final int SPINNER_OPTION_SECOND = 1;
public void onItemSelected(Adapt开发者_运维知识库erView<?> parent, View view, int pos, long id) {
switch(pos) {
case SPINNER_OPTION_FIRST: {
Toast.makeText(parent.getContext(), "0", Toast.LENGTH_LONG).show();
break;
}
case SPINNER_OPTION_SECOND: {
Toast.makeText(parent.getContext(), "1", Toast.LENGTH_LONG).show();
parent.findViewById(R.id.a_1).setVisibility(View.VISIBLE);
parent.findViewById(R.id.a_2).setVisibility(View.VISIBLE);
break;
}
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
Remember that View#findViewById
starts its search from the view you call it on and descends to its children. If the view with the ID you're looking for is not either the view itself or a descendant of that view, the search will fail and findViewById
will return null
.
As Falmarri suggests, you may not want to call findViewById
on parent
in that context. (You might also not want to call it on view
from there either.)
Where in your view hierarchy are you expecting to find R.id.a_1
?
精彩评论