我为每行设置了一个带有布局 XML 的 ListView :
this.setContentView(R.layout.item_view);
ListView m_ListView = this.getListView();
m_ListView.setTextFilterEnabled(true);
m_ListView.setItemsCanFocus(false);
m_ListView.setCacheColorHint(0x00000000);
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ArrayList<View> views=new ArrayList<View>();
e = mInflater.inflate(R.layout.item_first, null);
views.add(e);
r = mInflater.inflate(R.layout.item_second, null);
views.add(r);
mAdapter = new SillyAdapter(views);
setListAdapter(mAdapter);
现在,例如,我在 item_first
中有一个 TextView
,我想从代码中设置它:
TextView name = (TextView)findViewById(R.id.textView1);
name.setText(m_item.name);
但 name 始终为 null。知道为什么会发生这种情况吗?
最佳答案
您必须在代码中进行以下更改。
TextView name = (TextView)e.findViewById(R.id.textView1);
name.setText(m_item.name);
由于您从错误的 View 调用 findViewById 方法或者可能从 Activity 调用,因此您的 name 为 null。 因为你的充气方式如下
e = mInflater.inflate(R.layout.item_first, null);
您必须在膨胀 View 上调用 findViewById e。这样你就可以得到 xml R.layout.item_first
中包含的 id R.id.textView1 的 textview 实例希望这会有所帮助。
关于java - ListView 具有每行的自定义布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9955123/