4
我有一個自定義適配器的ListView圖像按鈕。我想根據列表中的條件在每行上設置ImageButton的可見性。但是,這些行並不包含我所設想的內容。如何顯示只在某些行
在下面我的例子中有一個財產count
稱爲ColorInfo
類。每當計數大於0時,我想顯示圖像。爲僞數據我已經與每個具有偶數項目計數填充在陣列的ColorInfo
20個元素大於0。然而,當我運行我沒有看到在交替行中的ImageButton
該應用
下面是一個完整的例子:
DemoActivity
public class DemoActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ColorInfo[] clr= new ColorInfo[20];
for(int i=0;i<20;i++){
ColorInfo clrInfo = new ColorInfo();
if (i%2 == 0) {
clrInfo.count = 5;
}
clr[i] = clrInfo;
}
((ListView)findViewById(R.id.list)).setAdapter(new MyAdapter(this, 0, clr));
}
private class MyAdapter extends ArrayAdapter<ColorInfo> {
ViewHolder holder;
LayoutInflater inflater;
public MyAdapter(Context context, int textViewResourceId,ColorInfo[] objects) {
super(context, textViewResourceId, objects);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
final ColorInfo item = getItem(position);
if(itemView == null){
itemView = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.editButton = (ImageButton) itemView.findViewById(R.id.some_button);
itemView.setTag(holder);
}
else
holder = (ViewHolder)itemView.getTag();
if (item.count>0)
holder.editButton.setVisibility(View.VISIBLE);
return itemView;
}
private class ViewHolder{
ImageButton editButton;
}
}
private static class ColorInfo{
int count = 0;
}
}
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
row.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="match_parent"
android:text="test"/>
<ImageButton
android:id="@+id/some_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:visibility="gone"
android:src="@drawable/ic_some_img"/>
</LinearLayout>
更新
我找到了答案here顯然因爲行是通過重複使用ArrayAdapter其良好的有一個else條件爲好。
所以我只是增加了一個'else'條件,現在它的工作。這個答案讓我:http://stackoverflow.com/a/4897545/3384340 – Anthony
這是完美的。我正要通過把一些條件能見度編輯這個答案。謝謝(你的)信息 .. :) – mike20132013