【问题标题】:ListViews with multiple item layouts具有多个项目布局的 ListView
【发布时间】:2010-08-05 15:35:34
【问题描述】:

我的ListActivity 上有一个ListView,我希望ListView 的行是3 种不同布局中的一种。我列表中的第一项始终使用布局 A,列表中的第二项始终使用布局 B,所有后续项目都将使用布局 C。

这是我的 getView 函数:

@Override
public View getView(int position, View convertView, ViewGroup parent) { 
    // get the View for this list item
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        switch (position) {
            case 0:
                v = vi.inflate(R.layout.layout_A, parent, false);
                break;
            case 1:
                v = vi.inflate(R.layout.layout_B, parent, false);
                break;
            default:
                v = vi.inflate(R.layout.layout_C, parent, false);
                break;
        }
    }   
    switch (position) {
        case 0:
            TextView txtLabel1 = (TextView)findViewById(R.id.label1);
            TextView txtLabel2 = (TextView)findViewById(R.id.label2);
            if (txtLabel1 != null) {
                txtLabel1.setText("sdfasd");
            }
            if (txtLabel2 != null) {
                txtLabel2.setText("dasgfadsasd");
            }
            break;
        default:
            break;
    }
    // return the created view
    return v;
}

R.id.label1R.id.label2R.layout.layout_A 上是 TextViews。但是,txtLabel1txtLabel2 在尝试设置它们后为空。为什么?

我在调试器中单步执行了这段代码,它膨胀了正确的布局 (R.layout.layout_A) 并落入下面的正确大小写以设置 R.id.label1R.id.label2 文本。

另外,如果有更好的方法,请告诉我。

【问题讨论】:

  • 检查this tutorial。他们解释了与您要实现的目标类似的内容。

标签: android listview layout


【解决方案1】:

看起来像“View v = convertView; if (v == null) {...”是个问题。您应该每次都重新创建视图,因为您不知道给定视图的类型。此外,您可以使用查看器方法来更有效地实施。您可以在此博客中找到一些想法:http://codinglines.frankiv.me/post/18486197303/android-multiple-layouts-in-dynamically-loading

【讨论】:

  • 这是一个非常糟糕的主意,会显着降低性能。 Macarse postet 是一个很好的例子,它无论如何都会尝试重用视图。
猜你喜欢
  • 1970-01-01
  • 2014-01-22
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多