Jordy Voorham
Jordy Voorham

Reputation: 67

Android: AdapterView select item

I have an AdapterView filled with items enter image description here

and I would like to select the item I click on, something like this:enter image description here is there a possible way I can do this?

This is how I build the adapter

adapter = new ArrayAdapter<String>(
                            context,
                            android.R.layout.simple_selectable_list_item,
                            QuestionActivity.OptionArrayList.get(position));
                    context.startActivity(i);

Upvotes: 1

Views: 576

Answers (2)

Nikhil Sharma
Nikhil Sharma

Reputation: 847

You need a custom adapter to achieve this. It will simply extend BaseAdater, and will have a custom view along with a boolean to keep info of which item was selected. You can follow Using a BaseAdapter with ListView guide.

CustomAdatpter class will be as follows -

public class MyAdapter extends BaseAdapter {

        private Context context;
        private ArrayList<String> arrayList;

        //taking boolean to keep track of item selected
        private boolean isItemSelected = false;

        public MyAdapter(Context context, ArrayList<String> arrayList) {
            this.context = context;
            this.arrayList = arrayList;
        }

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return arrayList.get(position); //returns list item at the specified position
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(context).
                        inflate(R.layout.item, parent, false);
            }

            TextView textView = (TextView) convertView.findViewById(R.id.text_view);
            textView.setText(arrayList.get(position));

            //setting click listener on convertView which is each item view
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isItemSelected){
                        //item is selected, need to un select item, 
                        isItemSelected = false;
                        textView.setBackgroundResource(R.drawable.unselected_bg);
                    }
                    else{
                        //item is not selected, need to select item
                        isItemSelected = true;
                        textView.setBackgroundResource(R.drawable.selected_bg);
                    }
                }
            });
            return convertView;
        }
    }

I am using R.drawable.unselected_bg and R.drawable.selected_bg which are nothing but drawable files as follows -

selected_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#5B5BC9"/>
    <stroke android:color="#4CAF50" android:width="5dp"/>
</shape>

unselected_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#5B5BC9"/>

</shape>

In last item has following layout which was inflated in getView();

item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="true"
    android:focusable="true"
    android:id="@+id/text_view"
    android:background="@drawable/unselected_bg"
    android:padding="16dp">

</TextView>

If you notice, I have given android:background="@drawable/unselected_bg" just to make item unselected on create.

Result will be as follows -

enter image description here

Happy Coding !

Upvotes: 0

iknow
iknow

Reputation: 9872

You can check this sample project I just made. I think the code speaks for itself but feel free to ask questions if You aren't sure about something. But basically I set OnItemClickListener to the ListView and I change the background to selected_back which is a shape in drawable folder. Also, I keep a reference to the last changed View so when user click on another View it will be easy to change its background again to normal_back.

MainActivity.java

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
{
    View lastChangedView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("One");
        arrayList.add("Two");
        arrayList.add("Three");

        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this,
                R.layout.list_view_item,
                arrayList);

        ListView listView = findViewById(R.id.listView);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                if (lastChangedView != null)
                {
                    lastChangedView.setBackgroundResource(R.drawable.normal_back);
                }
                lastChangedView = view;
                Log.d("Main", "Item click at " + position);
                view.setBackgroundResource(R.drawable.selected_back);
            }
        });
    }
}

acitivty_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

list_view_item.xml (in layout folder)

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="32sp"
    android:background="@drawable/normal_back" />

normal_back.xml (in a drawable folder)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFFFF" />
</shape>

selected_back.xml (in a drawable folder)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <stroke
        android:width="2dp"
        android:color="#0000FF" />
    <solid android:color="#FFFFFF" />
</shape>

Result (after clicking on "Two"):

enter image description here

Upvotes: 2

Related Questions