可扩展的ListView默认选择 [英] Expandable listview default selection

查看:139
本文介绍了可扩展的ListView默认选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立,内带一个可扩展的列表视图导航抽屉里。 我要的可扩展列表视图扩大集团之一,当活动开启了默认选择其孩子中的一个。用户可以根据自己的要求更改选择。

无论我创造是不符合我的要求。可膨胀列表允许用户选择多个选项。

MainActivity

 公共类MainActivity延伸活动{
    DrawerLayout mDrawerLayout;
    ExpandableListView mDrawerList;
    ExpandableListAdapter listAdapter;
    清单<串GT; listDataHeader;
    HashMap的<字符串列表<串GT;> listDataChild;
    私人动作条mActionBar;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        //用折叠图标操作栏菜单抽屉===================
        mActionBar = getActionBar();
        mActionBar.setHomeButtonEnabled(真);
        mActionBar.setDisplayHomeAsUpEnabled(假);
        //用折叠图标操作栏菜单抽屉===================        mDrawerLayout =(DrawerLayout)findViewById(R.id.drawer_layout);
        mDrawerList =(ExpandableListView)findViewById(R.id.left_drawer);        // preparing列表数据
        prepareListData();        listAdapter =新ExpandableListAdapter(这一点,listDataHeader,
                listDataChild);        //设置列表适配器
        mDrawerList.setAdapter(listAdapter);        //列表视图组单击监听器
        mDrawerList.setOnGroupClickListener(新OnGroupClickListener(){            @覆盖
            公共布尔onGroupClick(ExpandableListView父视图V,
                    INT groupPosition,长ID){
                // Toast.makeText(getApplicationContext(),
                //集团已点击+ listDataHeader.get(groupPosition)
                // Toast.LENGTH_SHORT).show();
                返回false;
            }
        });        // //列表视图集团扩大监听器
        // mDrawerList.setOnGroupExpandListener(新OnGroupExpandListener(){
        //
        // @覆盖
        //公共无效onGroupExpand(INT groupPosition){
        // Toast.makeText(getApplicationContext(),
        // listDataHeader.get(groupPosition)+展开,
        // Toast.LENGTH_SHORT).show();
        //}
        //});
        //
        // //列表视图组collasped监听器
        // mDrawerList.setOnGroupCollapseListener(新OnGroupCollapseListener()
        // {
        //
        // @覆盖
        //公共无效onGroupCollapse(INT groupPosition){
        // Toast.makeText(getApplicationContext(),
        // listDataHeader.get(groupPosition)+坍塌,
        // Toast.LENGTH_SHORT).show();
        //
        //}
        //});        // mDrawerList.expandGroup(2);
        // mDrawerList.expandGroup(2,真正的);        //列表视图儿童点击监听器
        mDrawerList.setOnChildClickListener(新OnChildClickListener(){            @覆盖
            公共布尔onChildClick(ExpandableListView父视图V,
                    INT groupPosition,诠释childPosition,长ID){                mDrawerLayout.closeDrawer(mDrawerList);
                // TODO自动生成方法存根
                // Toast.makeText(
                // getApplicationContext(),
                // listDataHeader.get(groupPosition)
                // +:
                // + listDataChild.get(
                // listDataHeader.get(groupPosition))。得到(
                // childPosition),Toast.LENGTH_SHORT)
                // 。显示();
                 v.setBackgroundColor(Color.BLUE);                makeAToast(本集团+ groupPosition +孩子:
                        + childPosition);
                返回false;
            }
        });        //要折叠previously打开组===========
        mDrawerList.setOnGroupExpandListener(新OnGroupExpandListener(){
            INT previousItem = -1;            @覆盖
            公共无效onGroupExpand(INT groupPosition){
                如果(groupPosition!= previousItem)
                    mDrawerList.collapseGroup(previousItem);
                previousItem = groupPosition;
            }
        });
        //要折叠previously打开组===========
    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        //充气菜单;如果是present这增加了项目操作栏。
        。getMenuInflater()膨胀(R.menu.main,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        开关(item.getItemId()){
        案例android.R.id.home:
            如果(mDrawerLayout.isDrawerOpen(mDrawerList)){
                mDrawerLayout.closeDrawer(mDrawerList);
            }其他{
                mDrawerLayout.openDrawer(mDrawerList);
            }
            打破;        默认:
            打破;
        }
        返回super.onOptionsItemSelected(项目);
    }    / *
     * preparing列表数据
     * /
    私人无效prepareListData(){
        listDataHeader =新的ArrayList<串GT;();
        listDataChild =新的HashMap<字符串列表<串GT;>();        //添加标题数据
        listDataHeader.add(今天);        //添加子数据
        清单<串GT;今天=新的ArrayList<串GT;();
        today.add(Tanushree哈);
        today.add(杜罗伊);
        today.add(潘辛格托马尔);
        today.add(米尔卡·辛格);
        today.add(罗希特拉马努金);
        today.add(拉梅什布哈特);
        today.add(Debjani梵天);        listDataHeader.add(明天);
        清单<串GT;明天=新的ArrayList<串GT;();
        tomorrow.add(Dipanjan Bhowmik);
        tomorrow.add(Sarmistha辛哈);
        tomorrow.add(Pranay Lalwani);
        tomorrow.add(莫希特肖);
        tomorrow.add(洛夫莱斯阿加瓦尔);
        tomorrow.add(Tanmay班纳吉);        listDataHeader.add(后来);
        清单<串GT;后来=新的ArrayList<串GT;();
        later.add(优素福汗);
        later.add(Jitendar夏尔马);
        later.add(Debashree罗伊);
        later.add(Mainak戈什);
        later.add(奥利维亚·戈麦斯);        listDataChild.put(listDataHeader.get(0)今天); //头,儿童数据
        listDataChild.put(listDataHeader.get(1),明日);
        listDataChild.put(listDataHeader.get(2),后);
    }    //方法来显示敬酒消息
    公共无效makeAToast(字符串str){
        吐司面包= Toast.makeText(这一点,STR,Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
    }
}

activity_main.xml中布局:

 <的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
的xmlns:工具=htt​​p://schemas.android.com/tool​​s
机器人:layout_width =match_parent
机器人:layout_height =match_parent
工具:上下文=MainActivity。>< android.support.v4.widget.DrawerLayout
    的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:ID =@ + ID / drawer_layout
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>
<的FrameLayout
    机器人:ID =@ + ID / content_frame
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>
< /&的FrameLayout GT; < - 安卓!layout_gravity =启动讲述DrawerLayout治疗
     以此为在左侧的滑动抽屉左到右
     语言和右侧从右到左的语言。
     抽屉被赋予了DP一个固定的宽度并延伸的全高
     的容器。的扎实的背景是用于对比
     与内容视图。 - >
< ExpandableListView
    机器人:ID =@ + ID / left_drawer
    机器人:layout_width =240dp
    机器人:layout_height =match_parent
    机器人:layout_gravity =开始
    机器人:choiceMode =singleChoice
    机器人:分=#999999
    机器人:dividerHeight =1DP
    机器人:背景=#FFFFFF/>
< /android.support.v4.widget.DrawerLayout>< / RelativeLayout的>

ExpandableListAdapter 类:

 公共类ExpandableListAdapter扩展BaseExpandableListAdapter {    私人语境_context;
    私人列表<串GT; _listDataHeader; //头标题
    //子数据头标题格式,标题子
    私人的HashMap<字符串列表<串GT;> _listDataChild;    公共ExpandableListAdapter(上下文的背景下,列表与LT;弦乐> listDataHeader,
            HashMap的<字符串列表<串GT;> listChildData){
        this._context =背景;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }    @覆盖
    公共对象getChild(INT groupPosition,诠释childPosititon){
        返回this._listDataChild.get(this._listDataHeader.get(groupPosition))
                获得(childPosititon);
    }    @覆盖
    众长getChildId(INT groupPosition,诠释childPosition){
        返回childPosition;
    }    @覆盖
    公共查看getChildView(INT groupPosition,最终诠释childPosition,
            布尔isLastChild,查看convertView,父母的ViewGroup){        最后弦乐childText =(字符串)getChild(groupPosition,childPosition);        如果(convertView == NULL){
            LayoutInflater infalInflater =(LayoutInflater)this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item,NULL);
        }        TextView的txtListChild =(TextView中)convertView
                .findViewById(R.id.lblListItem);        txtListChild.setText(childText);
        返回convertView;
    }    @覆盖
    公众诠释getChildrenCount(INT groupPosition){
        返回this._listDataChild.get(this._listDataHeader.get(groupPosition))
                。尺寸()​​;
    }    @覆盖
    公共对象getGroup(INT groupPosition){
        返回this._listDataHeader.get(groupPosition);
    }    @覆盖
    公众诠释getGroupCount(){
        返回this._listDataHeader.size();
    }    @覆盖
    众长getGroupId(INT groupPosition){
        返回groupPosition;
    }    @覆盖
    公共查看getGroupView(INT groupPosition,布尔isExpanded,
            查看convertView,父母的ViewGroup){
        字符串headerTitle =(字符串)getGroup(groupPosition);
        如果(convertView == NULL){
            LayoutInflater infalInflater =(LayoutInflater)this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group,NULL);
        }        TextView的lblListHeader =(TextView中)convertView
                .findViewById(R.id.lblListHeader);
        lblListHeader.setTypeface(NULL,Typeface.BOLD);
        lblListHeader.setText(headerTitle);        返回convertView;
    }    @覆盖
    公共布尔hasStableIds(){
        返回false;
    }    @覆盖
    公共布尔isChildSelectable(INT groupPosition,诠释childPosition){
        返回true;
    }}

如果需要再源$ C ​​$ C,我会提供它。我应该怎么做才能满足我的要求吗?


解决方案

有关问题的第一部分:


  

我要的可扩展列表视图扩大集团之一,并选择
  当活动开启其子在默认情况下的一个了。


  mExpandableListView.setSelectedChild(groupPosition,childPosition,shouldExpandGroup);

其中:


  1. groupPosition是应该首先扩大了集团的立场

  2. 应该是默认选中的孩子的位置*下面更多信息

  3. shouldExpandGroup是应该设置为true,扩大集团的布尔

信息以上2。


  1. 维护含有基团现在的位置,并用相同的用户所选择的子位置的散列映射

     的HashMap<整数,整数GT;地图=新的HashMap<整数,整数GT;();
    map.put(groupPosition,childPosition);


  2. 有关每一个孩子选择简单地把它放入HashMap的,它会覆盖值,如果present


  3. 保存此HashMap无论是在一个文件或地方在那里,你可以再次访问它(可以是共享preference但它不允许的对象存储)


  4. 在活动开始从散列表获取的价值,并设置选择,
    你可以对所有组但shouldExpand设置选择为false所有
    除了第一。如果地图是空集默认选择为0。


I have created a navigation drawer with an expandable listview inside it. I want the expandable listview to expand one of its groups and select one of its child by default when the activity opens up. The user may change the selection according to his requirement.

Whatever I have created is not satisfying my requirement. The expandable list is allowing the user to select multiple options.

The MainActivity:

public class MainActivity extends Activity {
    DrawerLayout mDrawerLayout;
    ExpandableListView mDrawerList;
    ExpandableListAdapter listAdapter;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;
    private ActionBar mActionBar;

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

        // Action bar with collapse icon for drawer menu===================
        mActionBar = getActionBar();
        mActionBar.setHomeButtonEnabled(true);
        mActionBar.setDisplayHomeAsUpEnabled(false);
        // Action bar with collapse icon for drawer menu===================

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ExpandableListView) findViewById(R.id.left_drawer);

        // preparing list data
        prepareListData();

        listAdapter = new ExpandableListAdapter(this, listDataHeader,
                listDataChild);

        // setting list adapter
        mDrawerList.setAdapter(listAdapter);

        // Listview Group click listener
        mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                    int groupPosition, long id) {
                // Toast.makeText(getApplicationContext(),
                // "Group Clicked " + listDataHeader.get(groupPosition),
                // Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        // // Listview Group expanded listener
        // mDrawerList.setOnGroupExpandListener(new OnGroupExpandListener() {
        //
        // @Override
        // public void onGroupExpand(int groupPosition) {
        // Toast.makeText(getApplicationContext(),
        // listDataHeader.get(groupPosition) + " Expanded",
        // Toast.LENGTH_SHORT).show();
        // }
        // });
        //
        // // Listview Group collasped listener
        // mDrawerList.setOnGroupCollapseListener(new OnGroupCollapseListener()
        // {
        //
        // @Override
        // public void onGroupCollapse(int groupPosition) {
        // Toast.makeText(getApplicationContext(),
        // listDataHeader.get(groupPosition) + " Collapsed",
        // Toast.LENGTH_SHORT).show();
        //
        // }
        // });

        // mDrawerList.expandGroup(2);
        // mDrawerList.expandGroup(2, true);

        // Listview on child click listener
        mDrawerList.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {

                mDrawerLayout.closeDrawer(mDrawerList);
                // TODO Auto-generated method stub
                // Toast.makeText(
                // getApplicationContext(),
                // listDataHeader.get(groupPosition)
                // + " : "
                // + listDataChild.get(
                // listDataHeader.get(groupPosition)).get(
                // childPosition), Toast.LENGTH_SHORT)
                // .show();
                 v.setBackgroundColor(Color.BLUE);

                makeAToast("Group: " + groupPosition + " Child: "
                        + childPosition);
                return false;
            }
        });

        // To collapse previously opened group===========
        mDrawerList.setOnGroupExpandListener(new OnGroupExpandListener() {
            int previousItem = -1;

            @Override
            public void onGroupExpand(int groupPosition) {
                if (groupPosition != previousItem)
                    mDrawerList.collapseGroup(previousItem);
                previousItem = groupPosition;
            }
        });
        // To collapse previously opened group===========
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    /*
     * Preparing the list data
     */
    private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        // Adding header data
        listDataHeader.add("Today");

        // Adding child data
        List<String> today = new ArrayList<String>();
        today.add("Tanushree Guha");
        today.add("Prasenjit Roy");
        today.add("Pan Singh Tomar");
        today.add("Milka Singh");
        today.add("Rohit Ramanujan");
        today.add("Ramesh Bhatt");
        today.add("Debjani Brahma");

        listDataHeader.add("Tomorrow");
        List<String> tomorrow = new ArrayList<String>();
        tomorrow.add("Dipanjan Bhowmik");
        tomorrow.add("Sarmistha Sinha");
        tomorrow.add("Pranay Lalwani");
        tomorrow.add("Mohit Shaw");
        tomorrow.add("Lovelace Agarwal");
        tomorrow.add("Tanmay Banerjee");

        listDataHeader.add("Later");
        List<String> later = new ArrayList<String>();
        later.add("Yusuf Khan");
        later.add("Jitendar Sharma");
        later.add("Debashree Roy");
        later.add("Mainak Ghosh");
        later.add("Olivia Gomes");

        listDataChild.put(listDataHeader.get(0), today); // Header, Child data
        listDataChild.put(listDataHeader.get(1), tomorrow);
        listDataChild.put(listDataHeader.get(2), later);
    }

    // method to show toast message
    public void makeAToast(String str) {
        Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
}

The activity_main.xml layout:

<RelativeLayout 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" >

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

 <!-- android:layout_gravity="start" tells DrawerLayout to treat
     this as a sliding drawer on the left side for left-to-right
     languages and on the right side for right-to-left languages.
     The drawer is given a fixed width in dp and extends the full height of
     the container. A solid background is used for contrast
     with the content view. -->
<ExpandableListView
    android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="#999999"
    android:dividerHeight="1dp"
    android:background="#ffffff"/>
</android.support.v4.widget.DrawerLayout>

</RelativeLayout>

The ExpandableListAdapter class:

public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private Context _context;
    private List<String> _listDataHeader; // header titles
    // child data in format of header title, child title
    private HashMap<String, List<String>> _listDataChild;

    public ExpandableListAdapter(Context context, List<String> listDataHeader,
            HashMap<String, List<String>> listChildData) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

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

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

        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item, null);
        }

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.lblListItem);

        txtListChild.setText(childText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

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

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group, null);
        }

        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.lblListHeader);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);

        return convertView;
    }

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

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

}

If anymore source code is required, I will provide it. What should I do to satisfy my requirement?

解决方案

For the first part of the question:

I want the expandable listview to expand one of its groups and select one of its child by default when the activity opens up

mExpandableListView.setSelectedChild(groupPosition, childPosition, shouldExpandGroup);

where :

  1. groupPosition is the position of the group that should be expanded first
  2. position of the child that should be selected by default *More info below
  3. shouldExpandGroup is a boolean that should be set to true to expand the group

Info for 2 above.

  1. Maintain a hashmap containing the group postion and the child position selected by the user like:

    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(groupPosition, childPosition);
    

  2. For every child selection simply put it into the hashmap, it would overwrite the value if present

  3. Store this hashmap either in a file or somewhere where you can access it again (may be shared preference but it does not allow storage of objects)

  4. When the activity starts get the value from the hashmap, and set the selection, you could set the selection for all the groups but with shouldExpand to false for all except the first. If the map is empty set default selection to 0.

这篇关于可扩展的ListView默认选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆