Sai*_*S.R 2 android android-view findviewbyid
我正在尝试实现自定义数组适配器,
问题是我使用时代码崩溃了
ImageView imageView=(ImageView)findViewById(R.id.imageView);
Run Code Online (Sandbox Code Playgroud)
而不是
ImageView imageView=(ImageView)rowView.findViewById(R.id.imageView);
Run Code Online (Sandbox Code Playgroud)
其中rowView是我已经实施的ListView的布局文件.
为什么会发生这种情况,我认为rowView.findViewById(R.id ..)只会让它更快地通过id找到元素,但没有它应用程序崩溃,你能解释一下吗?
这是我的活动代码
公共类MainActivity扩展AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Now for the list view
ListView listView=(ListView)findViewById(R.id.listView);
String[] values =new String[]{"iOS","android","firefoxOs","Ubuntu"};
MySimpleAdapter simpleAdapter=new MySimpleAdapter(this,values);
listView.setAdapter(simpleAdapter);
//
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class MySimpleAdapter extends ArrayAdapter<String>{
private Context context;
private String[] values;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//listView calls this on its adapter for each row
Log.v("list","getView");
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.custom_row,parent,false);
TextView textView1= (TextView) rowView.findViewById(R.id.textView1);
textView1.setText(values[position]);
//for the android row alone set an image , others leave it as blank
if(values[position].startsWith("and"))
{
ImageView imageView=(ImageView)rowView.findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher);//Ok R.drawale....is also an id
}
return rowView;
}
public MySimpleAdapter(Context context,String[] values) {
super(context, R.layout.custom_row,values);
this.context=context;
this.values=values;
Log.v("list","constructor");
}
}
Run Code Online (Sandbox Code Playgroud)
}
findViewById总是需要一个上下文来查找视图.
如果你从扩展Activity类的类调用它,你可以使用findViewById,因为Activity是上下文.
当你从一个扩展的类中调用它时fragment,你必须使用它getActivity().findViewById
在你的情况下,因为你在一个中调用它adapter,你需要在其中找到该视图listview row.所以你用view.findViewById
findViewById()用于在您的Activity. 例如,这是不可能的Fragment。view.findViewById()用于在特定的其他视图中查找视图。例如,ListView在行布局中查找视图。没有它,您的应用程序会崩溃,因为您要搜索的视图在rowView. 通过使用法线,findViewById()您将找不到视图。
| 归档时间: |
|
| 查看次数: |
6184 次 |
| 最近记录: |