简体   繁体   English

每行具有自定义布局的ListView

[英]ListView with custom layout for each row

I setup a listview with a layout XML for each row: 我为每行设置一个带有布局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);

now for example i have a TextView in item_first and i want to set it from the code: 现在例如,我在item_first有一个TextView ,我想从代码中进行设置:

    TextView name = (TextView)findViewById(R.id.textView1);
    name.setText(m_item.name);

but name is always null.any idea why it happen? 但是名字总是空的。知道为什么会发生吗?

You have to do the following changes in your code. 您必须在代码中进行以下更改。

TextView name = (TextView)e.findViewById(R.id.textView1);
name.setText(m_item.name);

You are getting name as null since you are calling findViewById method from wrong view or might be calling from activity. 由于从错误的视图调用findViewById方法或可能是从活动调用的,因此名称为null。 since you are inflating as follows 因为你膨胀如下

 e = mInflater.inflate(R.layout.item_first, null);

you have to call findViewById on inflated view e . 您必须在展开视图e上调用findViewById。 so that you will get the instance of textview with id R.id.textView1 contained in xml R.layout.item_first 这样您将获得包含在xml R.layout.item_first中的 ID为R.id.textView1的textview实例

Hope this will help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM