0
我有一個自定義列表視圖,其中每個項目包含一個imageview和一個textview。我希望用戶能夠點擊每個項目,並從下拉菜單中選擇一個新的imageview + textview組合。下拉菜單爲Android中的每個自定義ListView項目
下面是活動代碼
public class VisKvittering extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vis_kvittering);
String[] data = {"Old El Paso Papadums", "Redbull 0.33L", "Colgate Max White", "Kornbrød Sammenbakt", "Laksefilet m/skinn"};
Integer[] icons = {
R.drawable.transpbeef,
R.drawable.flaske,
R.drawable.kylling2,
R.drawable.transpbeef,
R.drawable.transpbeef,
};
String[] names = {
"Rødt kjøtt",
"Hvitt kjøtt",
"Fisk",
"Meieriprodukter"
};
CustomList customAdapter = new CustomList(VisKvittering.this, data, icons);
int counter = 0;
for (String product : data){
counter+= 1;
if (categorizer(product) == 0) {
icons[counter] = R.drawable.question;
customAdapter.setFlag(counter);
}
}
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(customAdapter);
}
//placeholder categorizer method
private int categorizer(String product){
if (product.charAt(0) == 'C'){
return 0;
} else {
return 1;
}
}}
下面是CustomList適配器類
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] products;
private final Integer[] imageId;
public CustomList(Activity context,
String[] products, Integer[] imageId) {
super(context, R.layout.list_single, products);
this.context = context;
this.products = products;
this.imageId = imageId;
}
int flag = -1;
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(products[position]);
//int colorPos = position % colors.length;
if (position == flag){
txtTitle.setTextColor(Color.RED);
} else {
txtTitle.setTextColor(Color.BLACK);
}
imageView.setImageResource(imageId[position]);
return rowView;
}
public void setFlag(int position){
this.flag = position;
}}
這裏的代碼列表項
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="@+id/img"
android:layout_width="50dp"
android:layout_height="50dp"/>
<TextView
android:id="@+id/txt"
android:textColor="@color/black"
android:layout_width="wrap_content"
android:gravity="center_vertical"
android:layout_height="50dp" />
</TableRow>
</TableLayout>