Android Listview为所选位置设置背景

时间:2014-04-08 07:08:07

标签: android listview android-listview

我在我的应用程序中有ListView,我有代码在所选项目上设置背景,现在代码在Android 3.0版中正常工作,当我在3.0以下运行相同的应用程序时(即2.3。 3)它不是将背景设置为所选项目,而是将背景设置为ListView中的其他项目,如果我点击ListView的第一项,它将背景设置为最后一项项目,如果我点击第二个项目然后它将背景设置为第二个项目,依此类推,只有当它来到中心项目正在为所选项目正确设置背景。

CustomlistAdapter.java

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.purchase_hadapter, null);

    TextView txtDate = (TextView)vi.findViewById(R.id.txtdate); 


    HashMap<String, String> listPurchaseHistory = new HashMap<String, String>();
    listPurchaseHistory = data.get(position);

    // Setting all values in listview
    txtDate.setText(listPurchaseHistory.get(PurchaseHistory.strTagDate));

    return vi;
}

MainActivity.java

  View selectedRow;
 lstPurchaseOption.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            if (selectedRow != null) {
                selectedRow.setBackgroundResource(color.transparent);
            }
            selectedRow = view;
            view.setBackgroundResource(R.drawable.list_background); 
        }
    });

1 个答案:

答案 0 :(得分:0)

我在ListView适配器中使用getView方法完成了一次:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = inflater.inflate(R.layout.mainmenu_item, parent, false);

    ...

    if(position == selectedValue){
        rowView.setBackgroundResource(R.drawable.active_menu_item);
    }
    else{
        rowView.setBackgroundResource(R.drawable.inactive_menu_item);
    }

    return rowView;
}

然后在onItemClickListner

mainMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {...
    mainMenulistAdapter.setSelectedValue(position);
    //redraws the list and sets backgrounds to elements
    mainMenulistAdapter.notifyDataSetInvalidated();
}