我似乎在应用程序崩溃:
parent.findViewById(R.id.a_1).setVisibility(View.VISIBLE);
不确定我做错了什么
代码在
之下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 包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(AdapterView<?> 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.
}
}
答案 0 :(得分:0)
请记住View#findViewById
从您调用它的视图开始搜索并下降到其子级。如果包含您要查找的ID的视图不是视图本身或该视图的后代,则搜索将失败,findViewById
将返回null
。
正如Falmarri建议的那样,您可能不希望在{1}}上呼叫findViewById
。 (您可能也不想在parent
从那里调用它。)
您希望在视图层次结构中找到view
?