1

I created a listview that is acting as a menu. When the user chooses a specific menu, another fragment will show up on the right portion.

Please see this image: Products The problem is, the icon and the title are only highlighted and not the whole selected row. How can I highlight the selected row instead of the icon and title only?

This is my code:

fragment_inventory_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".InventoryListFragment"
    android:layout_marginTop="@dimen/padding_50"
    android:orientation="vertical"
    android:background="?android:attr/activatedBackgroundIndicator">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical">

       <ListView
           android:id="@+id/inventorylist_listview"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:choiceMode="singleChoice"
           android:listSelector="@color/light_gray"/>

   </LinearLayout>


</LinearLayout>

InventoryListFragment.java

package com.example.devcash;


import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.devcash.CustomAdapters.InventoryListAdapter;
import com.example.devcash.Fragments.CategoriesFragment;
import com.example.devcash.Fragments.DiscountsFragment;
import com.example.devcash.Fragments.ProductsFragment;
import com.example.devcash.Fragments.ServicesFragment;
import com.example.devcash.Lists.InventoryList;

import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 */
public class InventoryListFragment extends Fragment implements AdapterView.OnItemClickListener {

    ListView lvinventory;
    ArrayList<InventoryList> list = new ArrayList<InventoryList>();
    InventoryListAdapter adapter;


    public InventoryListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_inventory_list, container, false);

        lvinventory = (ListView) view.findViewById(R.id.inventorylist_listview);
        adapter = new InventoryListAdapter(getActivity(),list);

        list.add(new InventoryList(R.drawable.ic_product,"Products"));
        list.add(new InventoryList(R.drawable.ic_services,"Services"));
        list.add(new InventoryList(R.drawable.ic_category, "Categories"));
        list.add(new InventoryList(R.drawable.ic_local_offer,"Discounts"));

        lvinventory.setAdapter(adapter);
        lvinventory.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InventoryList selectedList = this.list.get(position);

        int icon = selectedList.getIcon();
        String title = selectedList.getInventory_title();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (position){
            case 0:
                ProductsFragment productsFragment = new ProductsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, productsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 1:
                ServicesFragment servicesFragment = new ServicesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, servicesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case  2:
                CategoriesFragment categoriesFragment = new CategoriesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, categoriesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 3:
                DiscountsFragment discountsFragment = new DiscountsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, discountsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
        }
    }
}
Nikunj Paradva
  • 15,332
  • 5
  • 54
  • 65
no_profile
  • 387
  • 5
  • 15
  • You are already using a Custom Adapter class `InventoryListAdapter` . Just have an integer for selected position and set the background for this .[See this thread](https://stackoverflow.com/questions/27105222/custom-listview-with-only-one-checkbox-is-selected-one-at-a-time). – ADM May 28 '19 at 03:56
  • Thank you for your response. I have tried using `getListView().setSelector(..)` but `getListview()` is showing as red. – no_profile May 28 '19 at 04:05
  • Add `InventoryListAdapter` with question .. And `getListView()` is probably a method of `PrefrenceFragment` i guess so you can not use it ,, – ADM May 28 '19 at 04:08
  • Hi, still not working – no_profile May 28 '19 at 04:27
  • I don't know what you need but I think your design can be easily achieved by navigation drawer (https://developer.android.com/guide/navigation/navigation-ui). And if you can't use that for some reasons then try changing ListView android:layout_width="wrap_content" to "match_parent". – Sunil Sunny May 28 '19 at 05:25
  • I think this will help you: https://stackoverflow.com/questions/16976431/change-background-color-of-selected-item-on-a-listview – Divyesh May 28 '19 at 05:37
  • @sunilsunny I already have a navigation drawer. As you can see in the picture above, there is a hamburger icon. – no_profile May 28 '19 at 10:09
  • could you please past your item view layout – ismail alaoui May 28 '19 at 13:34
  • Please check my answer. - @BeverlyCastillo – Sagar Vekariya May 31 '19 at 05:20

4 Answers4

0

in your adapter getView() , just add a click listener and set the background color

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


 view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           view.setBackgroundColor(Color.GREY);
        }
    });
     ....
     ....

    return view;
  }
ismail alaoui
  • 5,748
  • 2
  • 21
  • 38
0

Try this

private class InventoryListAdapter extends ... {                
    private int focusedPosition = -1; // -1 means nothing is selected
    ....
    ....

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        if (position == focusedPosition) {
            view.setBackgroundColor(/* your selected color */);
        } else {
            view.setBackgroundColor(/* your NOT selected color */);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { 
               focusedPosition = position;
               notifyDataSetChanged();
            }
        });

        return view;
    }
Quick learner
  • 10,632
  • 4
  • 45
  • 55
Ferran
  • 1,442
  • 1
  • 6
  • 10
0

I would recommend to use recyclerview over listview , like @Ferran already answered for listview

RecyclerView vs. ListView

i would like to answer the same for recyclerview

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.ViewHolder> {
        private int selected_position = -1;

        @Override
        public void onBindViewHolder(PlacesLocationAdapter.ViewHolder holder, final int position) {
            if (selected_position == position) {
                // do your stuff here like
                //Change selected item background color and Show sub item views

            } else {
                  // do your stuff here like
                  //Change  unselected item background color and Hide sub item views
            }
  // rest of the code here

    holder.linelayout.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              if(selected_position==position){
                        selected_position=-1;
                        notifyDataSetChanged();
                        return;
                    }
                    selected_position = position;
                    notifyDataSetChanged();

            }
        });

    //rest of the code here

     }


}
Quick learner
  • 10,632
  • 4
  • 45
  • 55
0

In InventoryList Model add another one field like isSelected.

String isSelected;

public String getIsSelected() {
    return isSelected;
}

public void setIsSelected(String isSelected) {
    this.isSelected = isSelected;
}

And then By default set Value 0 of isSelected field. if you want to open by default Product fragment then its value is 1.

list.add(new InventoryList(R.drawable.ic_product,"Products","1"));
list.add(new InventoryList(R.drawable.ic_services,"Services","0"));
list.add(new InventoryList(R.drawable.ic_category, "Categories","0"));
list.add(new InventoryList(R.drawable.ic_local_offer,"Discounts","0"));

lvinventory.setAdapter(adapter);
lvinventory.setOnItemClickListener(this);

In onItemClick function to write below code :

for (int i = 0; i < list.size(); i++) {
    list.get(i).setIsSelected("0");
}

selectedList.setIsSelected("1");
adapter.notifyDataSetChanged();

In 'InventoryListAdapter' file 'getView' override function to set background color like ...

if (list.get(position).getIsSelected().equals("1")) {
    view.setBackgroundColor(/* your selected color */); // Gray
} else {
   view.setBackgroundColor(/* your NOT selected color */); // White
}
Sagar Vekariya
  • 212
  • 1
  • 2
  • 6