【问题标题】:How to Highlight the `Selected row` in a `Listview` using Fragments如何使用片段突出显示“列表视图”中的“选定行”
【发布时间】:2019-05-28 18:12:03
【问题描述】:

我创建了一个充当菜单的列表视图。当用户选择特定菜单时,另一个片段将显示在右侧部分。

请看这张图片: 问题是,图标和标题只突出显示,而不是整个选定的行。如何突出显示选定的行而不是仅显示图标和标题?

这是我的代码:

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;
        }
    }
}

【问题讨论】:

  • 您已经在使用自定义适配器类 InventoryListAdapter 。只需为所选位置设置一个整数并为此 .See this thread 设置背景。
  • 感谢您的回复。我尝试过使用getListView().setSelector(..),但getListview() 显示为红色。
  • 添加InventoryListAdapter 有问题.. 而getListView() 可能是PrefrenceFragment 的一种方法我猜所以你不能使用它,,
  • 嗨,还是不行
  • 我不知道您需要什么,但我认为您的设计可以通过抽屉式导航轻松实现 (developer.android.com/guide/navigation/navigation-ui)。如果由于某些原因您不能使用它,请尝试将 ListView android:layout_width="wrap_content" 更改为 "match_parent"。

标签: android listview fragment


【解决方案1】:

在您的适配器 getView() 中,只需添加一个点击监听器并设置背景颜色

@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;
  }

【讨论】:

  • 使用这个之前选中的项目颜色不会被清除。
  • @Piyush,你有什么建议吗?
【解决方案2】:

试试这个

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;
    }

【讨论】:

    【解决方案3】:

    我建议使用 recyclerview 而不是 listview ,就像 @Ferran 已经回答了 listview 一样

    RecyclerView vs. ListView

    我想为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
    
         }
    
    
    }
    

    【讨论】:

      【解决方案4】:

      InventoryList 模型中添加另一个字段,例如 isSelected。

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

      然后默认设置 isSelected 字段的值0。如果要默认打开 Product 片段,则其值为 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);
      

      onItemClick函数中写下代码:

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

      在 'InventoryListAdapter' 文件中的 'getView' 覆盖函数来设置背景颜色...

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-19
        • 2012-06-10
        • 2015-06-20
        • 2013-12-22
        • 1970-01-01
        • 1970-01-01
        • 2013-10-26
        • 2013-01-26
        相关资源
        最近更新 更多