我正在使用自定義適配器,並且getView方法有問題。這裏是我的代碼 -如何將多個textView添加到列表查看
@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>
其實我的指令是否工作,但其他空白的TextView也出現吧。 假設如果位置== 0,則應顯示「@ + id/text1」,但「@ + id/text2」也會顯示爲不帶文本。 我只想要顯示一個文本視圖,而不是另一個。怎麼做?
您可以動態設置視圖的可見性。如果你想要顯示它,可以使用'text2.setVisibility(View.VISIBLE)'或者如果你想隱藏它,使用'text2.setVisibility(View.GONE)'。 – zgc7009
非常感謝。 –