Skip to main content

Simple way to show menu items on list item get selected

Here is the most easier way to showing menu items on list items get selected. Your Activity will look like this
public class MainActivity extends AppCompatActivity {

    private RecyclerView myList;
    private int selectedCount;
    private ArrayList list;
    private MyListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        myList = (RecyclerView) findViewById(R.id.myList);
        myList.setHasFixedSize(true);
        myList.setLayoutManager(new LinearLayoutManager(this));

        list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add(new Item("Row " + (i + 1)));
        }

        adapter = new MyListAdapter(list, this);
        myList.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return selectedCount > 0;
    }

    public void onLongClicked(int adapterPosition) {
        list.get(adapterPosition).isSelected = true;
        selectedCount++;
        adapter.notifyDataSetChanged();
        invalidateOptionsMenu();
    }

    public void onClicked(int adapterPosition) {
        if (selectedCount > 0) {
            Item item = list.get(adapterPosition);
            if (item.isSelected) {
                selectedCount--;
            } else {
                selectedCount++;
            }
            item.setSelected(!item.isSelected);
            adapter.notifyDataSetChanged();
            invalidateOptionsMenu();
        }
    }
}
And your adapter will look like,
public class MyListAdapter extends RecyclerView.Adapter {
    private ArrayList myList;
    private MainActivity activity;

    public MyListAdapter(ArrayList myList, MainActivity mainActivity) {
        this.myList = myList;
        activity = mainActivity;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.textView.setText(myList.get(position).text);

        if (myList.get(position).isSelected) {
            holder.view.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorAccent));
        }else {
            holder.view.setBackgroundColor(Color.WHITE);
        }
        holder.view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                activity.onLongClicked(holder.getAdapterPosition());
                return true;
            }
        });

        holder.view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.onClicked(holder.getAdapterPosition());
            }
        });
    }

    @Override
    public int getItemCount() {
        return myList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        View view;
        TextView textView;

        public ViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            textView = itemView.findViewById(R.id.text);
        }
    }
}
And your Item class will look like,
public class Item {
    boolean isSelected;
    String text;

    public Item(String text) {
        this.text = text;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}
And your activity_main layout will look like,
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.guna.testapplication.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
And your content_main layout will look like,
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.guna.testapplication.MainActivity"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myList"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
And your menu_main will look like,
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.guna.testapplication.MainActivity">
    <item
        android:id="@+id/action_share"
        android:title="@string/share"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_delete"
        android:orderInCategory="100"
        android:title="@string/delete"
        app:showAsAction="never" />
</menu>
And your my_list_item layout will look like

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="1dp"
    android:background="#fff"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp" />
</LinearLayout>


Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Thank You



Comments

Popular posts from this blog

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml. Ex : import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import android.widget.Toast.LENGTH_LONG import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //String array. val myStrings = arrayOf("One", "Two", "Three", "Four", "Five") //Adapter for spinner mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_i...

Simple example of Navigation view on both side in Android

Hi guys, you can use NavigationView on both side if you want side menu in both left and right side in Android as following. Your drawer layout will be &lt?xml version="1.0" encoding="utf-8"?&gt &ltandroid.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"&gt &ltinclude layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /&gt &ltandroid.support.design.widget.NavigationView android:id="@+id/nav_view" ...

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter. As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way. RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); list.setHasFixedSize(true); ArrayList&ltNumber&gt numbers = new ArrayList&lt&gt(); String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"}; String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUND...