Listview
を使用し て を生成 しましたBaseAdapter
。現在、Listview には 4 行あります。行にいくつかの Textviews と Button があります。現在、ボタンの色はデフォルトの灰色です。私は次のことをしたい:
- 最初の行のボタンをクリックすると、ボタンの色を黒に変更したいと思います。
- 2 行目をクリックすると、1 行目のボタンが灰色に戻り、2 行目のボタンの色が黒に変わります。
要するに、クリックしたときに一度に1つのボタンだけを黒色にしたいのです。次のコードを実行しましたが、次の問題が発生します。
- 最初の行のボタンをクリックすると、3 番目の行のボタンが黒色になります。
- 2 行目のボタンをクリックすると黒くなりますが、前にクリックしたボタンは元の色に戻りません。
私は自分のコードを投稿しています。私はこれに非常に慣れていないので、順を追って説明してください。
mycontactstemp.java
public class contactstemp extends Fragment {
public ArrayList<ProductModel> _productlist = new ArrayList<ProductModel>();
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.viewrecord, container,
false);
return view;
}
private class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return _productlist.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return _productlist.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
viewHolder = new ViewHolder();
viewHolder.txt_pname = (TextView) convertView
.findViewById(R.id.txtdisplaypname);
viewHolder.txt_pprice = (TextView) convertView
.findViewById(R.id.txtdisplaypprice);
viewHolder.txtidno = (TextView) convertView
.findViewById(R.id.txtdisplaypid);
viewHolder.buttons = (Button) convertView
.findViewById(R.id.btn_update);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_pname.setText(_productlist.get(position)
.getProductname().trim());
viewHolder.txt_pprice.setText(_productlist.get(position)
.getProductprice().trim());
viewHolder.txtidno.setText(_productlist.get(position).getIdno()
.trim());
viewHolder.buttons.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewHolder.buttons.setBackgroundColor(Color.BLACK);
}
});
return convertView;
}