我有一个包含8个项目的listView。每个项目都包含一个单一按钮。我希望当每个列表项单击该项的背景更改时。我使用baseAdapter并且所有东西都是正确的,除非单击第一个项目(零位置),然后背景不会改变。这是我的适配器:
class MainListAdapter extends BaseAdapter implements View.OnClickListener {
ViewHolder viewHolder ;
int SelectedItem = 55 ;// dummy integer
Button[] buttons = new Button[8];
@Override
public int getCount() {
return MainListTitle.size();// array of string
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view==null){
// inflate the layout
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.main_list_item, viewGroup ,false);
// well set up the ViewHolde
viewHolder = new ViewHolder();
viewHolder.Title = (Button) view.findViewById(R.id.mainListButton);
viewHolder.Title.setText(MainListTitle.get(i));
viewHolder.Title.setId(i);
buttons[i]=viewHolder.Title ;
viewHolder.Title.setOnClickListener(this);
//store the holder with the view.
view.setTag(viewHolder);
}else{
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
viewHolder = (ViewHolder) view.getTag();
}
return view;
}
@Override
public void onClick(View view) {
// Toast.makeText(getApplicationContext(),view.getId()+"",Toast.LENGTH_SHORT).show();
switch (view.getId()){
case 0:
onButtonSelcted(0);
break;
case 1:
onButtonSelcted(1);
break;
case 2:
onButtonSelcted(2);
break;
case 3:
onButtonSelcted(3);
break;
case 4:
onButtonSelcted(4);
break;
case 5:
onButtonSelcted(5);
break;
case 6:
onButtonSelcted(6);
break;
case 7:
onButtonSelcted(7);
break;
}
}
class ViewHolder{
Button Title ;
}
private void onButtonSelcted(int position){
if (SelectedItem == position){}
else {
buttons[position].setBackgroundColor(getResources().getColor(R.color.white));
if (SelectedItem != 55){
buttons[SelectedItem].setBackgroundColor(getResources().getColor(R.color.material_blue_grey_900));
}
SelectedItem = position ;
}
}
答案 0 :(得分:0)
您需要使用setId()设置正数(大于零),如文档所述: http://developer.android.com/reference/android/view/View.html#setId%28int%29
你可能
...
viewHolder.Title.setId(i + 1);
...
然后
...
switch (view.getId() - 1){
...