Set a background color to a selected ListView Item

2020-02-09 09:09发布

I have a listview which displays several items. Now I want to scroll to some specific item (e.g. the 33th item). I know that this can be done via

myList.setSelection(32);

But on the UI the item doesn't receive any highlighting (because it is in touch mode?!). How can I apply a specific background color for this item? I tried

myList.getSelection().getSelectedView().setBackgroundColor(Color.Red);

but i get a NullPointerException because getSelectedView() returns null. Is there a way to achieve this highlighting? I have to notify the user somehow about which item is the "active" one...

7条回答
不美不萌又怎样
2楼-- · 2020-02-09 09:56

I tried by the following way and solved the problem.

Created a javaBean class that receives the position. Like following.

public class Global {

    public static int mListPosition = 0;

    public static int getListPosition() {
        return mListPosition;
    }

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

Then from The OnListItemClickListener() I set the position of the selected item. Like following

mList.setOnItemClickListener(new OnItemClickListener() {

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

Then in the adapter class do the following

@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.image1);
    } else {
        mHolder.mDetailsRetailerLayout
                .setBackgroundResource(R.drawable.image2);
    }

    if (mDetailsRetailerBean != null) {
        Log.i("Global Position", "" + Global.getListPosition());
        mHolder.mDetailsRetailer.setText(mDetailsRetailerBean
                .getRetailerName());
    }
    return v;
}    

Try this one to change the Selected row background color change in Android List view.

查看更多
登录 后发表回答