简体   繁体   中英

Highlight listView selection background programmatically

I have a ListView with a simple ArrayAdapter

dogsList.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dogsArray));

If a user clicks on an item, the background color changes. So far so great.

Here is my problem: when the user returns, I want to pre-highlight the last selection. I have tried a number of things to pre-highlight one of the entries but it's not working.

Assume I know the previous selection and pass it through intent or whatever, say prev=5 . How do I highLight the background?

I am using a real device (Note 5) to test. And I don't understand whether this applies or not: Android ListView programmatic selection/highlight . In any case, I did it and it didn't work: no highlight.

May be this will help

  View row = null;

   list_view.post(new Runnable() {
        @Override
        public void run() {
            int nPos = Prev;

            list_view.setSelection(nPos);
            View v = list_view.getChildAt(nPos);
            if (v != null) {
                option_list.performItemClick(v, nPos, list_view.getItemIdAtPosition(nPos));
                v.requestFocus();
            }
        }
    });
  list_view.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position,
                long arg3) {
            // TODO Auto-generated method stub

             if (row != null) {
                    row.setBackgroundResource(R.color.DarkGray);
                }
                row = v;
                v.setBackgroundResource(R.color.White);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM