【问题标题】:setText() of TextView in list_row.xmllist_row.xml 中 TextView 的 setText()
【发布时间】:2023-03-28 23:30:01
【问题描述】:

我有:

  1. 一个MyListActivity class extends ListActivitysetContentView(R.layout.mylist);
  2. 两个 xml 文件:mylist.xmllist_row.xml
  3. mylist.xml 是布局,list_row.xml 是每一行的样子。
  4. list_row.xml 包含 3 个 TextViews(t1,t2,t3)

我想更改 MyListActivity 类中 t2 的一些文本。因为内容视图是 mylist.xml 所以我不能简单地使用findViewById。所以我用了LayoutInflater

    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.list_row, null);

    textView2 = (TextView) v.findViewById(R.id.t2);
    textView2.setText("ccccc");

问题是 t2 的文本永远不会改变。我尝试了很多次,文本仍然是我在list_row.xml中设置的文本。我不知道为什么..有人可以帮忙。谢谢!

=====解决方案:=====

创建我自己的SimpleCursorAdapter 类并覆盖getView() 方法。

private class MySimpleCursorAdapter extends SimpleCursorAdapter {
    Cursor c;
    public MySimpleCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);
        this.c = c;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        super.getView(position, convertView, parent);
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.list_row, parent, false);
        TextView textview1 = (TextView) rowView.findViewById(R.id.text1);
        textView1.setText(c.getString(1));// whatever should be in textView1
        textView2 = (TextView) rowView.findViewById(R.id.text2);
        textView2.setText("ccccc");
        return rowView;
    }
}

super.getView(position, convertView, parent); 非常重要,因为如果我没有该行,textView1 将始终显示第一行的值(例如,如果textView1 显示 id,则它始终为 1)。

【问题讨论】:

    标签: android android-layout android-listview


    【解决方案1】:

    如果您想更改TextView 文本,您必须在ListView 的适配器中进行。

    【讨论】:

    • 您好,感谢您的回复。我有一个 SimpleCursorAdaper,我一直是 public View newView (Context context, Cursor cursor, ViewGroup parent),它“从指定的 XML 文件膨胀视图”和 public abstract View getView (int position, View convertView, ViewGroup parent),我可以从 XML 文件膨胀。但在 API 中,并没有说明如何充气。你能提供一个例子的链接吗?非常感谢
    • 另一个问题。根视图是列表视图吗?每一行都是列表视图的子视图?
    • 是的,问题解决了!刚刚添加MySimpleCursorAdapter 并覆盖getView() 并在那里更改文本。原来getView() 是由适配器为每一行调用的。谢谢!
    • @Dongminator 如果要对行进行任何更改,您必须实现自己的适配器并覆盖getView()(此方法的全部目的是在ListView 时给您一行要求它)方法来更改行的外观以及您在该特定行中放入的数据。你说你用SimpleCursorAdapter所以你也可以看看developer.android.com/reference/android/widget/…
    • 最后一个问题:现在我可以更改 textview2 的文本,但永远不会绘制每一行的 text1。这是为什么呢?
    【解决方案2】:

    更改文本视图的最佳方法是在getView()。请参阅 this 示例以获得更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      相关资源
      最近更新 更多