📜  Android中的BaseExpandableListAdapter示例

📅  最后修改于: 2021-05-08 19:27:11             🧑  作者: Mango

在许多android应用中,开发人员可能需要显示巨大的主要数据项的多数据。例如,按照我们的示例,在“编程语言”下,我们需要显示“Python”,“Java”等,在“关系数据库”下,我们需要显示“ Oracle”,“ MySQL”等,为此,我们可以使用“ BaseExpandableListAdapter ”。它是UI组件和填充UI组件中的数据的数据源之间的桥梁。它保存数据,然后将数据发送到Adapter视图,然后该视图可以从Adapter视图中获取数据,并在诸如ExpandableListView之类的不同视图上显示数据。它将提供对子级数据(按组分类)的访问,并为子级和组实例化视图。下面的样本GIF给出得到什么我们将在本文中做的想法注意,我们将使用Java语言实现该项目。

Android中的BaseExpandableListAdapter

让我们通过代码查看。这是CustomizedAdapter的代码片段。 Java文件:

Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
  
public class CustomizedAdapter extends BaseExpandableListAdapter {
  
    private Context context;
    private ArrayList mainSetName;
  
    public CustomizedAdapter(Context context, ArrayList deptList) {
        this.context = context;
        this.mainSetName = deptList;
    }
  
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        ArrayList productList = mainSetName.get(groupPosition).getSubsetName();
        return productList.get(childPosition);
    }
  
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }
  
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View view, ViewGroup parent) {
  
        ChildInfo detailInfo = (ChildInfo) getChild(groupPosition, childPosition);
        if (view == null) {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = infalInflater.inflate(R.layout.child_items, null);
        }
        TextView childItem = (TextView) view.findViewById(R.id.childItm);
        childItem.setText(detailInfo.getName().trim());
  
        return view;
    }
  
    @Override
    public int getChildrenCount(int groupPosition) {
  
        ArrayList productList = mainSetName.get(groupPosition).getSubsetName();
        return productList.size();
  
    }
  
    @Override
    public Object getGroup(int groupPosition) {
        return mainSetName.get(groupPosition);
    }
  
    @Override
    public int getGroupCount() {
        return mainSetName.size();
    }
  
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }
  
    @Override
    public View getGroupView(int groupPosition, boolean isLastChild, View view,
                             ViewGroup parent) {
  
        GroupInformation headerInfo = (GroupInformation) getGroup(groupPosition);
        if (view == null) {
            LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inf.inflate(R.layout.group_items, null);
        }
  
        TextView heading = (TextView) view.findViewById(R.id.data);
        heading.setText(headerInfo.getName().trim());
  
        return view;
    }
  
    @Override
    public boolean hasStableIds() {
        return true;
    }
  
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
  
}


XML


  
    
  


XML


  
    
  


XML


  
    
  


Java
public class ChildInfo {
    private String name = "";
      
    // Getter , setter methods
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
}


Java
import java.util.ArrayList;
  
public class GroupInformation {
  
    private String mainSetName;
    private ArrayList list = new ArrayList();
  
    public String getName() {
        return mainSetName;
    }
  
    public void setName(String mainSetName) {
        this.mainSetName = mainSetName;
    }
  
    public ArrayList getSubsetName() {
        return list;
    }
  
    public void setSubsetName(ArrayList subSetName) {
        this.list = subSetName;
    }
  
}


Java
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.LinkedHashMap;
  
public class MainActivity extends AppCompatActivity {
  
    private LinkedHashMap mainSet = new LinkedHashMap();
    private ArrayList subSet = new ArrayList();
  
    private CustomizedAdapter listAdapter;
    private ExpandableListView simpleExpandableListView1;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // add data for displaying in expandable list view
        loadData();
  
        // get reference of the ExpandableListView from activity_main
        simpleExpandableListView1 = (ExpandableListView) findViewById(R.id.simpleExpandableListView1);
          
        // create the adapter and by passing your ArrayList data
        listAdapter = new CustomizedAdapter(MainActivity.this, subSet);
        simpleExpandableListView1.setAdapter(listAdapter);
  
        // setOnChildClickListener listener for child row click, so that we can get the value
        simpleExpandableListView1.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                // get the group header
                GroupInformation headerInfo = subSet.get(groupPosition);
                // get the child info
                ChildInfo detailInfo = headerInfo.getSubsetName().get(childPosition);
                // display it or do something with it
                Toast.makeText(getBaseContext(), headerInfo.getName() + "/" + detailInfo.getName(), Toast.LENGTH_LONG).show();
                return false;
            }
        });
          
        // setOnGroupClickListener listener for group heading click
        simpleExpandableListView1.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                // get the group header
                GroupInformation headerInfo = subSet.get(groupPosition);
                // display it or do something with it
                Toast.makeText(getBaseContext(), headerInfo.getName(), Toast.LENGTH_LONG).show();
                return false;
            }
        });
    }
  
    // load some initial data into out list
    private void loadData() {
  
        addDetails("Programming_Languages", "Python");
        addDetails("Programming_Languages", "Java");
        addDetails("Programming_Languages", "Kotlin");
        addDetails("Programming_Languages", "NodeJS");
        addDetails("Programming_Languages", "GO");
  
        addDetails("Relational_Database", "Oracle");
        addDetails("Relational_Database", "SQLServer");
        addDetails("Relational_Database", "MySQL");
  
        addDetails("NoSQL_Database", "MongoDB");
        addDetails("NoSQL_Database", "Cassandra");
        addDetails("NoSQL_Database", "CouchDB");
  
    }
      
    // here we maintain main set like Programming languages and subsets like Python
    private int addDetails(String mainSet, String subSet) {
  
        int groupPosition = 0;
  
        // check the hash map if the group already exists
        GroupInformation headerInfo = this.mainSet.get(mainSet);
          
        // add the group if doesn't exists
        if (headerInfo == null) {
            headerInfo = new GroupInformation();
            headerInfo.setName(mainSet);
            this.mainSet.put(mainSet, headerInfo);
            this.subSet.add(headerInfo);
        }
  
        // get the children for the group
        ArrayList subList = headerInfo.getSubsetName();
          
        // size of the children list
        int listSize = subList.size();
          
        // add to the counter
        listSize++;
  
        // create a new child and add that to the group
        ChildInfo detailInfo = new ChildInfo();
        detailInfo.setName(subSet);
        subList.add(detailInfo);
        headerInfo.setSubsetName(subList);
  
        // find the group position inside the list
        groupPosition = this.subSet.indexOf(headerInfo);
        return groupPosition;
    }
}


查看方法getChildView()getGroupView() 。它们用于创建与布局相对应的视图。

方法1:

方法2:

方法3:

方法4:

方法5:

方法6:

方法7:

方法8:

方法9:

例子

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。

XML格式



  
    
  

步骤3:建立新的XML档案

转到应用程序> res>布局>右键单击>新建>布局资源文件,并将文件命名为child_items 。以下是child_items.xml文件的代码。这里,TextView用于项目的子集,例如: Python

XML格式



  
    
  

同样,创建另一个布局资源文件并将该文件命名为group_items 。以下是group_items.xml文件的代码。这里,TextView用于主要项目集,例如: Programming_Languages

XML格式



  
    
  

步骤4:建立新的Java档案

转到应用程序> Java >包名称>右键单击>新建> Java Classe ,并将文件命名为ChildInfo 。下面是ChildInfo的代码。 Java文件。

Java

public class ChildInfo {
    private String name = "";
      
    // Getter , setter methods
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
}

同样,创建另一个Java类文件,并将文件命名为CustomizedAdapter 。我们已经在开始部分讨论了这一点,并且还讨论了每种重写的方法。因此,您可以复制相同的代码并在项目中实现它。

现在创建另一个Java文件,并将文件命名为GroupInformation 。下面是GroupInformation的代码。 Java文件。

Java

import java.util.ArrayList;
  
public class GroupInformation {
  
    private String mainSetName;
    private ArrayList list = new ArrayList();
  
    public String getName() {
        return mainSetName;
    }
  
    public void setName(String mainSetName) {
        this.mainSetName = mainSetName;
    }
  
    public ArrayList getSubsetName() {
        return list;
    }
  
    public void setSubsetName(ArrayList subSetName) {
        this.list = subSetName;
    }
  
}

步骤5:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.LinkedHashMap;
  
public class MainActivity extends AppCompatActivity {
  
    private LinkedHashMap mainSet = new LinkedHashMap();
    private ArrayList subSet = new ArrayList();
  
    private CustomizedAdapter listAdapter;
    private ExpandableListView simpleExpandableListView1;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // add data for displaying in expandable list view
        loadData();
  
        // get reference of the ExpandableListView from activity_main
        simpleExpandableListView1 = (ExpandableListView) findViewById(R.id.simpleExpandableListView1);
          
        // create the adapter and by passing your ArrayList data
        listAdapter = new CustomizedAdapter(MainActivity.this, subSet);
        simpleExpandableListView1.setAdapter(listAdapter);
  
        // setOnChildClickListener listener for child row click, so that we can get the value
        simpleExpandableListView1.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                // get the group header
                GroupInformation headerInfo = subSet.get(groupPosition);
                // get the child info
                ChildInfo detailInfo = headerInfo.getSubsetName().get(childPosition);
                // display it or do something with it
                Toast.makeText(getBaseContext(), headerInfo.getName() + "/" + detailInfo.getName(), Toast.LENGTH_LONG).show();
                return false;
            }
        });
          
        // setOnGroupClickListener listener for group heading click
        simpleExpandableListView1.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                // get the group header
                GroupInformation headerInfo = subSet.get(groupPosition);
                // display it or do something with it
                Toast.makeText(getBaseContext(), headerInfo.getName(), Toast.LENGTH_LONG).show();
                return false;
            }
        });
    }
  
    // load some initial data into out list
    private void loadData() {
  
        addDetails("Programming_Languages", "Python");
        addDetails("Programming_Languages", "Java");
        addDetails("Programming_Languages", "Kotlin");
        addDetails("Programming_Languages", "NodeJS");
        addDetails("Programming_Languages", "GO");
  
        addDetails("Relational_Database", "Oracle");
        addDetails("Relational_Database", "SQLServer");
        addDetails("Relational_Database", "MySQL");
  
        addDetails("NoSQL_Database", "MongoDB");
        addDetails("NoSQL_Database", "Cassandra");
        addDetails("NoSQL_Database", "CouchDB");
  
    }
      
    // here we maintain main set like Programming languages and subsets like Python
    private int addDetails(String mainSet, String subSet) {
  
        int groupPosition = 0;
  
        // check the hash map if the group already exists
        GroupInformation headerInfo = this.mainSet.get(mainSet);
          
        // add the group if doesn't exists
        if (headerInfo == null) {
            headerInfo = new GroupInformation();
            headerInfo.setName(mainSet);
            this.mainSet.put(mainSet, headerInfo);
            this.subSet.add(headerInfo);
        }
  
        // get the children for the group
        ArrayList subList = headerInfo.getSubsetName();
          
        // size of the children list
        int listSize = subList.size();
          
        // add to the counter
        listSize++;
  
        // create a new child and add that to the group
        ChildInfo detailInfo = new ChildInfo();
        detailInfo.setName(subSet);
        subList.add(detailInfo);
        headerInfo.setSubsetName(subList);
  
        // find the group position inside the list
        groupPosition = this.subSet.indexOf(headerInfo);
        return groupPosition;
    }
}

输出:

在模拟器上运行应用程序时,我们可以查看视频中的输出。此功能是许多应用程序中非常需要的功能。

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!