如何更改在android中选择的列表项的背景

时间:2012-11-20 12:37:38

标签: android android-listview

  

可能重复:
  how to change selected list item background, android

在设置屏幕中的Android平板电脑中,列表中列表项的背景会发生变化,直到用户进行下一次选择,这是使该功能正常工作的标准方法。直到现在我对所选项目使用了布尔值,我刷新了列表以反映每次点击后的更改,我不这样做,这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

You can use the following process . It works fine.

   Write a Global bean that get the postion of the selected item from the list.

     public class Global {      
        public static int mListPosition = 0; 

        public static int getListPosition() {
                return mListPosition;
            }    
        public static void setListPosition(int mListPosition) {
                Global.mListPosition = mListPosition;
            }   

        }

from List onClickListener set the position into the global bean


mList.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                Global.setListPosition(arg2);
mAdapter.notifyDataSetChanged();
}
        });



in the adapter 

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.details_retailer_list_row, null);

                mHolder = new ViewHolder();
                v.setTag(mHolder);

                mHolder.mDetailsRetailerLayout = (LinearLayout) v.findViewById(R.id.details_cart_retailer_row_layout);
                mHolder.mDetailsRetailer = (TextView) v.findViewById(R.id.detailsRetailerRow);

            }
            else {
                mHolder =  (ViewHolder) v.getTag();
            }           


            final CartDetailsRetailerBean mDetailsRetailerBean = mItems.get(position);
            if (position == Global.getListPosition()) {
                mHolder.mDetailsRetailerLayout
                        .setBackgroundResource(R.drawable.row_white);
            } else {
                mHolder.mDetailsRetailerLayout
                        .setBackgroundResource(R.drawable.row_red);
            }

            if(mDetailsRetailerBean != null){

                Log.i("Global Position", ""+Global.getListPosition());



                mHolder.mDetailsRetailer.setText(mDetailsRetailerBean.getRetailerName());

            }

            return v;
        }

        class ViewHolder {
            public LinearLayout mDetailsRetailerLayout;
            public TextView mDetailsRetailer;

        }


Please apply it . I think it will work fine.