Android 可扩展列表

发布于 2024-11-17 21:55:36 字数 506 浏览 7 评论 0原文

我正在尝试将自定义 ExpandableListView 与父级和子级布局以及父级 XML 和子级 XML 结合使用。

我的数据将是服务器响应。因此,我最好希望以数组列表或哈希映射的形式获取父级和子级布局的数据,

我将包含我想要的图像。

有没有办法通过任何 + 或 - UI 表示来更改可扩展列表箭头图像(默认),如下所示。

列表

List1

请针对这种特定情况提出教程或代码逻辑。

I am trying to use a custom ExpandableListView with parent and child layout with a parent XML and child XML.

My data would be a server response. So I preferably would like to have data in the form of an Array List or Hash-map for parent and child layouts

I am enclosing the images of what I want.

Is there any way to change the expandable list arrow image(Default) by any + or - UI representation as shown below.

List

List1

Please suggest a tutorial or code logic for this specific situation .

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

掩于岁月 2024-11-24 21:55:36

经过研发后D over Expandable List 我发现expandable List-view是Android提供的一个两级树形视图。

该视图包含两种类型的类别。

第一种类型是Group-Elements,第二种类型是Child-Elements,也称为父元素和子元素。

此示例的主要目的是自定义可扩展列表视图,如问题中的图片所示。

我已经介绍了我在经历中遇到的一些有关可扩展列表视图的重要主题。

下面的代码是 main.xml 包含可扩展的列表视图。
main.xml

<!--?xml version="1.0" encoding="UTF-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

     <expandablelistview android:id="@+id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:groupindicator="@drawable/group_indicator.xml">

     <textview android:id="@+id/android:empty" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/main_no_items">       
</textview></expandablelistview></linearlayout>

group_row.xml 如下,包含可扩展列表组视图的布局structure.group_row.xml

     <textview android:id="@+id/tvGroupName" android:layout_width="wrap_content" android:layout_height="40dip" android:textsize="16sp" android:textstyle="bold" android:paddingleft="30dip" android:gravity="center_vertical">

child_row.xml 这是包含可扩展列表视图组结构的布局。
child_row.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="40dip" android:gravity="center_vertical">

    <textview android:id="@+id/tvPlayerName" android:paddingleft="50dip" android:textsize="14sp" android:layout_width="wrap_content" android:layout_height="30dip" android:gravity="center_vertical">

</textview></linearlayout>

首先从xml读取可扩展列表视图的引用到活动类。

 public class ExpList extends ExpandableListActivity
    {
     /**
      * strings for group elements
      */
        static final String arrGroupelements[] = 
        {
       "India",
       "Australia",
       "England",
       "South Africa"
     };

        /**
      * strings for child elements
      */
     static final String arrChildelements[][] = 
     {
       {
      "Sachin Tendulkar",
      "Raina",
      "Dhoni",
      "Yuvi"
       },
       {
      "Ponting",
      "Adam Gilchrist",
      "Michael Clarke"
       },
       {
      "Andrew Strauss",
      "kevin Peterson",
      "Nasser Hussain"
       },
       {
      "Graeme Smith",
      "AB de villiers",
      "Jacques Kallis"
       }
        };

     DisplayMetrics metrics;
     int width;
     ExpandableListView expList;

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            expList = getExpandableListView();
            metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            width = metrics.widthPixels;
            //this code for adjusting the group indicator into right side of the view


if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            expList.setIndicatorBounds(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));
        } else {
            expList.setIndicatorBoundsRelative(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));
        }

            expList.setAdapter(new ExpAdapter(this));

      expList.setOnGroupExpandListener(new OnGroupExpandListener()
      {
       @Override
       public void onGroupExpand(int groupPosition) 
       {
        Log.e("onGroupExpand", "OK");
       }
      });

      expList.setOnGroupCollapseListener(new OnGroupCollapseListener()
      {
       @Override
       public void onGroupCollapse(int groupPosition) 
       {
        Log.e("onGroupCollapse", "OK");
       }
      });

      expList.setOnChildClickListener(new OnChildClickListener()
      {
       @Override
       public boolean onChildClick(ExpandableListView parent, View v,
         int groupPosition, int childPosition, long id) {
        Log.e("OnChildClickListener", "OK");
        return false;
       }
      });
        }

        public int GetDipsFromPixel(float pixels)
        {
         // Get the screen's density scale
         final float scale = getResources().getDisplayMetrics().density;
         // Convert the dps to pixels, based on density scale
         return (int) (pixels * scale + 0.5f);
        }
    }

对于自定义 Exp Listview 主要是适配器。 Android 提供了 BaseExpandableListAdapter 用于自定义视图。下面是Adapter的设计代码。

这是用于构造组和子元素的可扩展列表视图的适配器。

public class ExpAdapter extends BaseExpandableListAdapter {

  private Context myContext;
  public ExpAdapter(Context context) {
   myContext = context;
  }
  @Override
  public Object getChild(int groupPosition, int childPosition) {
   return null;
  }

  @Override
  public long getChildId(int groupPosition, int childPosition) {
   return 0;
  }

  @Override
  public View getChildView(int groupPosition, int childPosition,
    boolean isLastChild, View convertView, ViewGroup parent) {

   if (convertView == null) {
    LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.child_row, null);
   }

   TextView tvPlayerName = (TextView) convertView.findViewById(R.id.tvPlayerName);
   tvPlayerName.setText(arrChildelements[groupPosition][childPosition]);

   return convertView;
  }

  @Override
  public int getChildrenCount(int groupPosition) {
   return arrChildelements[groupPosition].length;
  }

  @Override
  public Object getGroup(int groupPosition) {
   return null;
  }

  @Override
  public int getGroupCount() {
   return arrGroupelements.length;
  }

  @Override
  public long getGroupId(int groupPosition) {
   return 0;
  }

  @Override
  public View getGroupView(int groupPosition, boolean isExpanded,
    View convertView, ViewGroup parent) {

   if (convertView == null) {
    LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.group_row, null);
   }

   TextView tvGroupName = (TextView) convertView.findViewById(R.id.tvGroupName);
   tvGroupName.setText(arrGroupelements[groupPosition]);

   return convertView;
  }

  @Override
  public boolean hasStableIds() {
   return false;
  }

  @Override
  public boolean isChildSelectable(int groupPosition, int childPosition) {
   return true;
  }
 }

group_indicator.xml
这是用于更改默认指示器图像的代码。

 <?xml version="1.0" encoding="UTF-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_expanded="true" android:drawable="@drawable/friend_small" />
        <item android:drawable="@drawable/place_small" />
    </selector>

After a R & D over expandable List I found that expandable List-view is a two level tree view provided by Android.

This view contains two types of categories.

First type is Group-Elements and second one is Child-Elements, also called parent and child elements.

The main aim of this example is to customize the expandable list-view as the picture in the question shows.

I have covered some important topics about expandable list-view that I faced during my experiences.

Below code is main.xml contains the expandable list-view.
main.xml

<!--?xml version="1.0" encoding="UTF-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

     <expandablelistview android:id="@+id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:groupindicator="@drawable/group_indicator.xml">

     <textview android:id="@+id/android:empty" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/main_no_items">       
</textview></expandablelistview></linearlayout>

the group_row.xml is as follows that contains the layout for Expandable list group view structure.group_row.xml
?

     <textview android:id="@+id/tvGroupName" android:layout_width="wrap_content" android:layout_height="40dip" android:textsize="16sp" android:textstyle="bold" android:paddingleft="30dip" android:gravity="center_vertical">

child_row.xml this is contains the layout for Expandable list view group structure.
child_row.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="40dip" android:gravity="center_vertical">

    <textview android:id="@+id/tvPlayerName" android:paddingleft="50dip" android:textsize="14sp" android:layout_width="wrap_content" android:layout_height="30dip" android:gravity="center_vertical">

</textview></linearlayout>

First read the reference of the expandable listview from xml to activity class.

 public class ExpList extends ExpandableListActivity
    {
     /**
      * strings for group elements
      */
        static final String arrGroupelements[] = 
        {
       "India",
       "Australia",
       "England",
       "South Africa"
     };

        /**
      * strings for child elements
      */
     static final String arrChildelements[][] = 
     {
       {
      "Sachin Tendulkar",
      "Raina",
      "Dhoni",
      "Yuvi"
       },
       {
      "Ponting",
      "Adam Gilchrist",
      "Michael Clarke"
       },
       {
      "Andrew Strauss",
      "kevin Peterson",
      "Nasser Hussain"
       },
       {
      "Graeme Smith",
      "AB de villiers",
      "Jacques Kallis"
       }
        };

     DisplayMetrics metrics;
     int width;
     ExpandableListView expList;

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            expList = getExpandableListView();
            metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            width = metrics.widthPixels;
            //this code for adjusting the group indicator into right side of the view


if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            expList.setIndicatorBounds(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));
        } else {
            expList.setIndicatorBoundsRelative(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));
        }

            expList.setAdapter(new ExpAdapter(this));

      expList.setOnGroupExpandListener(new OnGroupExpandListener()
      {
       @Override
       public void onGroupExpand(int groupPosition) 
       {
        Log.e("onGroupExpand", "OK");
       }
      });

      expList.setOnGroupCollapseListener(new OnGroupCollapseListener()
      {
       @Override
       public void onGroupCollapse(int groupPosition) 
       {
        Log.e("onGroupCollapse", "OK");
       }
      });

      expList.setOnChildClickListener(new OnChildClickListener()
      {
       @Override
       public boolean onChildClick(ExpandableListView parent, View v,
         int groupPosition, int childPosition, long id) {
        Log.e("OnChildClickListener", "OK");
        return false;
       }
      });
        }

        public int GetDipsFromPixel(float pixels)
        {
         // Get the screen's density scale
         final float scale = getResources().getDisplayMetrics().density;
         // Convert the dps to pixels, based on density scale
         return (int) (pixels * scale + 0.5f);
        }
    }

For customising the Exp Listview main thing is adapter. Android provides BaseExpandableListAdapter for customising the view. Bellow is the code for design of Adapter.

This is adapter for expandable list-view for constructing the group and child elements.

public class ExpAdapter extends BaseExpandableListAdapter {

  private Context myContext;
  public ExpAdapter(Context context) {
   myContext = context;
  }
  @Override
  public Object getChild(int groupPosition, int childPosition) {
   return null;
  }

  @Override
  public long getChildId(int groupPosition, int childPosition) {
   return 0;
  }

  @Override
  public View getChildView(int groupPosition, int childPosition,
    boolean isLastChild, View convertView, ViewGroup parent) {

   if (convertView == null) {
    LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.child_row, null);
   }

   TextView tvPlayerName = (TextView) convertView.findViewById(R.id.tvPlayerName);
   tvPlayerName.setText(arrChildelements[groupPosition][childPosition]);

   return convertView;
  }

  @Override
  public int getChildrenCount(int groupPosition) {
   return arrChildelements[groupPosition].length;
  }

  @Override
  public Object getGroup(int groupPosition) {
   return null;
  }

  @Override
  public int getGroupCount() {
   return arrGroupelements.length;
  }

  @Override
  public long getGroupId(int groupPosition) {
   return 0;
  }

  @Override
  public View getGroupView(int groupPosition, boolean isExpanded,
    View convertView, ViewGroup parent) {

   if (convertView == null) {
    LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.group_row, null);
   }

   TextView tvGroupName = (TextView) convertView.findViewById(R.id.tvGroupName);
   tvGroupName.setText(arrGroupelements[groupPosition]);

   return convertView;
  }

  @Override
  public boolean hasStableIds() {
   return false;
  }

  @Override
  public boolean isChildSelectable(int groupPosition, int childPosition) {
   return true;
  }
 }

group_indicator.xml
This the code for changing the default indicator image.

 <?xml version="1.0" encoding="UTF-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_expanded="true" android:drawable="@drawable/friend_small" />
        <item android:drawable="@drawable/place_small" />
    </selector>
旧情勿念 2024-11-24 21:55:36

与此同时
我创建了一个selector.xml为:

<?xml version="1.0" encoding="UTF-8"?>

<selector xmlns:android="schemas.android.com/apk/res/android" >

    <item
        android:drawable="@drawable/friend_small"
        android:state_expanded="true"/>

    <item android:drawable="@drawable/place_small"/>
</selector>

并在xml中的android:groupIndicator="@drawable/selector"中给出 -friend_small 和 placesmall 是我的展开和折叠状态的图像

In the meanwhile
I have created an selector.xml as:

<?xml version="1.0" encoding="UTF-8"?>

<selector xmlns:android="schemas.android.com/apk/res/android" >

    <item
        android:drawable="@drawable/friend_small"
        android:state_expanded="true"/>

    <item android:drawable="@drawable/place_small"/>
</selector>

and given in android:groupIndicator="@drawable/selector" in xml – friend_small and place small are my images of expand and collapsed state

流年里的时光 2024-11-24 21:55:36

您可以通过调用 更改指示器设置组指示符

可展开列表能够在每个项目旁边显示一个指示器,以显示该项目的当前状态(状态通常是展开组、折叠组、子项或最后一个子项之一)。使用 setChildIndicator(Drawable) 或 setGroupIndicator(Drawable) (或相应的 XML 属性)来设置这些指示符(请参阅每个方法的文档以查看每个 Drawable 可以具有的其他状态)。

另外,您需要自己实现 ExpandableListAdapter。可能会在其中夸大自己对父母和孩子的看法。

you can change the indicator by calling setGroupIndicator

Expandable lists are able to show an indicator beside each item to display the item's current state (the states are usually one of expanded group, collapsed group, child, or last child). Use setChildIndicator(Drawable) or setGroupIndicator(Drawable) (or the corresponding XML attributes) to set these indicators (see the docs for each method to see additional state that each Drawable can have).

also, you need your own implementation of an ExpandableListAdapter. it's possible to inflate your own views for both parents and children in it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文