【问题标题】:How to add more than one textView to listView如何将多个textView添加到listView
【发布时间】:2016-11-10 19:52:02
【问题描述】:

我正在使用自定义适配器,但我遇到了 getView 方法的问题。这是我的代码-

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi = convertView;
        if (vi == null)
            vi = inflater.inflate(R.layout.list_item, null);
     if(position==0){
        TextView text1 = (TextView) vi.findViewById(R.id.text1);
        text1.setText(data[position]);
     }else if(position==1){
        TextView text2 = (TextView) vi.findViewById(R.id.text2);
        text2.setText(data[position]);
      }
        return vi;
    }

这里是 XML 文件 -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAlignment="center"
    android:background="@android:color/black"
    android:textColor="@android:color/white"
    android:id="@+id/text1" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAlignment="center"
    android:background="@android:color/green"
    android:textColor="@android:color/white"
    android:id="@+id/text2" />


</LinearLayout>

实际上我的 if 命令正在工作,但另一个空白 textView 也随之出现。 假设如果 position==0 则应该显示“@+id/text1”,但“@+id/text2”也不会显示任何文本。 我只想显示一个文本视图,而不是另一个。该怎么做?

【问题讨论】:

  • 您可以动态设置视图的可见性。 text2.setVisibility(View.VISIBLE) 如果你想显示它,text2.setVisibility(View.GONE) 如果你想隐藏它。

标签: android listview custom-adapter


【解决方案1】:

position 是适配器中当前显示项的索引,而不是正在显示的 TextView。

适配器的每一行都有两个 TextView,我假设您有一些字符串需要在两个视图中显示。

举个例子,试试这个。

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    String item = String.valueOf(data[position]);

    View v = convertView;
    if (v == null) {
        v = inflater.inflate(R.layout.list_item, null);
    }

    TextView text1 = (TextView) v.findViewById(R.id.text1);
    TextView text2 = (TextView) v.findViewById(R.id.text2);

    text1.setText("1: " + item);
    text2.setText("2: " + item);

    return v;
}

我只想显示一个文本视图,而不是另一个。该怎么做?

那么听起来你不想在一个布局中使用两个 TextView...

如果您的问题是“如何在 ListView 中显示多个 TextView”,那么您应该将多个值放入该 data 数组中。

【讨论】:

  • 我的问题是当这个 [text1.setText("1: " + item);] 被执行然后 text2 也得到显示,其中没有文本。
  • 我的回答不应该发生这种情况
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多