三个级别的ListView在ExpandableListView

三个级别的ListView在ExpandableListView

本文介绍了如何添加三个级别的ListView在ExpandableListView在安卓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想补充的ExpandableListView.In当前ExpandableListView在更多层面上是两级我如何增加一个级别。我是新的Andr​​oid的发展,请帮助我。提前致谢!

我的MainActivity.java: -

 专用工具栏mToolbar;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
名单<字符串> listDataHeader;
HashMap的<字符串列表与LT;字符串>> listDataChild;

//私人FragmentDrawer drawerFragment;
ArrayList的<字符串> arraylist1,arraylist2,arraylist3,arrayList4,arrayList5;
INT CNT = 0;

@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    mToolbar =(工具栏)findViewById(R.id.toolbar);

    setSupportActionBar(mToolbar);
    getSupportActionBar()setDisplayShowHomeEnabled(真)。

    expListView =(ExpandableListView)findViewById(R.id.lvExp);

    // preparing列表数据
    prepareListData();

    listAdapter =新ExpandableListAdapter(这一点,listDataHeader,listDataChild);

    //设置列表适配器
    expListView.setAdapter(listAdapter);

   / * drawerFragment =(FragmentDrawer)
            。getSupportFragmentManager()findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout),mToolbar);
    drawerFragment.setDrawerListener(本); * /
    //显示在应用程序启动的第一个抽屉式导航视图
  // displayView(0);
    Log.d(onCreate方法,);
    arraylist1 =新的ArrayList<字符串>();
    arraylist2 =新的ArrayList<字符串>();
    arraylist3 =新的ArrayList<字符串>();
    arrayList4 =新的ArrayList<字符串>();
    arrayList5 =新的ArrayList<字符串>();
    新ProductsAsynTask().execute("http://opencart.$c$cniques.com/shopping/?route=feed/web_api/menu&key=test123$");


}
私人无效prepareListData(){
    listDataHeader =新的ArrayList<字符串>();
    listDataChild =新的HashMap<字符串列表与LT;字符串>>();


    //添加子数据
    listDataHeader.add(250强);
    listDataHeader.add(现在显示);
    listDataHeader.add(即将推出。);

    //添加子数据
    名单<字符串> TOP250 =新的ArrayList<字符串>();
    top250.add(肖申克的救赎);
    top250.add(教父);
    top250.add(教父:第二部分);
    top250.add(低俗小说);
    top250.add(黄金三镖客);
    top250.add(黑暗骑士);
    top250.add(12怒汉);

    名单<字符串> nowShowing =新的ArrayList<字符串>();
    nowShowing.add(招魂);
    nowShowing.add(卑鄙的我2);
    nowShowing.add(涡轮);
    nowShowing.add(大人2);
    nowShowing.add(红2);
    nowShowing.add(以下简称金刚狼);

    名单<字符串> comingSoon =新的ArrayList<字符串>();
    comingSoon.add(2枪);
    comingSoon.add(蓝精灵2);
    comingSoon.add(以下简称壮观现在);
    comingSoon.add(大峡谷);
    comingSoon.add(欧罗巴报告);

    listDataChild.put(listDataHeader.get(0),TOP250); //头,子数据
    listDataChild.put(listDataHeader.get(1),nowShowing);
    listDataChild.put(listDataHeader.get(2),comingSoon);
}

公共类ProductsAsynTask扩展的AsyncTask<字符串,太虚,太虚> {

    ProgressDialog对话框;

    在preExecute保护无效(){
        super.on preExecute();
        Log.d(在上preExceute,);
        对话框=新ProgressDialog(MainActivity.this);
        dialog.setMessage(载入中,请稍候);
        dialog.setTitle(连接服务器);
        dialog.show();
        dialog.setCancelable(假);
    }

    保护无效doInBackground(字符串...参数){
        尝试{
            Log.d(以doInBackground,);

            HttpClient的客户端=新DefaultHttpClient();
            HttpPost后=新HttpPost(参数[0]);
            HTT presponse响应= client.execute(后);

            。INT状态= response.getStatusLine()的getStatus code();

            如果(状态== 200){
                Log.d(状态,+状态);

                HttpEntity实体= response.getEntity();
                字符串数据= EntityUtils.toString(实体);

                的JSONObject的JSONObject =新的JSONObject(数据);
                JSONArray jArray = jsonObject.getJSONArray(类);

                的for(int i = 0; I< jArray.length();我++){
                    CNT ++;
                    Log.d(数组的值,jArray.length()+);
                    Log.d(i的值,+ I);

                    的JSONObject jsonObject1 = jArray.getJSONObject(ⅰ);


                    arraylist1.add(jsonObject1.getString(名字));
                    //数据1 = jsonObject1.getString(姓名);
              // Log.d(你好,DATA1);

                    JSONArray jsonArray = jsonObject1.getJSONArray(儿童);
         // JSONObject的jsonObject2 = jsonObject1.getJSONObject(儿童);

                    对于(INT J = 0; J< jsonArray.length(); J ++){

                        JSONObject的jsonObject2 = jsonArray.getJSONObject(J);

                        arraylist2.add(jsonObject2.getString(名字));
                      //数据2 = jsonObject2.getString(姓名);
                        JSONArray jsonArray1 = jsonObject2.getJSONArray(children_lv3);

                        对于(INT K = 0; K< jsonArray1.length(); k ++){
                            JSONObject的jsonObject3 = jsonArray1.getJSONObject(K);

                            arraylist3.add(jsonObject3.getString(名字));
                            arrayList4.add(jsonObject3.getString(HREF));
                           / *数据3 = jsonObject3.getString(姓名);
                             DATA4 = jsonObject3.getString(HREF); * /
                        }
                        arrayList5.add(jsonObject2.getString(HREF));
                      //数据5 = jsonObject2.getString(HREF);
                    }
                }

            }
        }赶上(IOException异常E){
            Log.e(错误IOException异常:,e.getMessage());
        }赶上(JSONException E){
            Log.e(错误JSONException,e.getMessage());
        }
            返回null;
    }

    保护无效onPostExecute(虚空避免){
        super.onPostExecute(避免);
        dialog.dismiss();
        Log.d(反价值,+ CNT);
    }
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单;这增加了项目操作栏,如果它是present。
    。getMenuInflater()膨胀(R.menu.menu_main,菜单);
    返回true;
}

@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    //处理动作栏项目点击这里。将操作栏
    //自动在主/向上按钮操作的点击,只要
    //你在AndroidManifest.xml中指定一个父活动。
    INT的id = item.getItemId();

    // noinspection SimplifiableIfStatement
    如果(ID == R.id.action_settings){
        返回true;
    }

    如果(ID == R.id.action_search){
        Toast.makeText(getApplicationContext(),搜寻动作被选择!,Toast.LENGTH_SHORT).show();
        返回true;
    }

    返回super.onOptionsItemSelected(项目);
}


 / *公共无效onDrawerItemSelected(查看视图,INT位置){
    displayView(位置);
}

私人无效displayView(INT位置){
    片段片段= NULL;
    字符串标题=的getString(R.string.app_name);
    开关(位置){
        情况下0:

           片段=新HomeFragment();
           标题=的getString(R.string.title_home);
            打破;
        情况1:
            片段=新FriendsFragment();
            标题=的getString(R.string.title_friends);
            打破;
        案例2:
            片段=新MessagesFragment();
            标题=的getString(R.string.title_messages);
            打破;
        默认:
            打破;
    }

    如果(片段!= NULL){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body,片段);
        fragmentTransaction.commit();

        //设置工具栏标题
        getSupportActionBar()的setTitle(职称)。
    }
} * /}
 

我的ExpandableListAdapter.java是在这里: -

 公共类ExpandableListAdapter扩展BaseExpandableListAdapter {

私人语境_context;
私人列表<字符串> _listDataHeader; //标题标题
//子数据的标题标题格式,子标题
私人的HashMap<字符串列表与LT;字符串>> _listDataChild;

公共ExpandableListAdapter(上下文的背景下,列表与LT;字符串> listDataHeader,
                             HashMap的<字符串列表与LT;字符串>> 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;
}}
 

我的activity_main.xml是在这里: -

 < android.support.v4.widget.DrawerLayout
的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:ID =@ + ID / drawer_layout
机器人:layout_width =FILL_PARENT
机器人:layout_height =FILL_PARENT>


<的LinearLayout
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直>

    <的LinearLayout
        机器人:ID =@ + ID / container_toolbar
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:方向=垂直>

        <包括
            机器人:ID =@ + ID /工具栏
            布局=@布局/工具栏/>


    < / LinearLayout中>

    <的FrameLayout
        机器人:ID =@ + ID / container_body
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =0dp
        机器人:layout_weight =1/>




< / LinearLayout中>

< ExpandableListView
    机器人:ID =@ + ID / lvExp
    机器人:layout_height =match_parent
    机器人:layout_width =260dp
    机器人:layout_gravity =开始/>
    <! - <片段
    机器人:ID =@ + ID / fragment_navigation_drawer
    机器人:名称=com.android.ShoppingMazza.activity.ExpandableListAdapter
    机器人:layout_width =@扪/ nav_drawer_width
    机器人:layout_height =match_parent
    机器人:layout_gravity =开始
    应用程序:布局=@布局/ fragment_navigation_drawer
    工具:布局=@布局/ fragment_navigation_drawer/> - >
  < /android.support.v4.widget.DrawerLayout>
 

解决方案

activity_main.xml

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT>

    < ExpandableListView
     机器人:layout_width =FILL_PARENT
     机器人:ID =@ + ID / ParentLevel
     机器人:groupIndicator =@空
     机器人:layout_height =FILL_PARENT>
    < / ExpandableListView>

< / LinearLayout中>
 

MainActivity.Java

 进口android.app.Activity;
进口android.content.Context;
进口android.graphics.Color;
进口android.os.Bundle;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.BaseExpandableListAdapter;
进口android.widget.ExpandableListView;
进口android.widget.ListView;

进口android.widget.TextView;

进口android.widget.LinearLayout.LayoutParams;


公共类家庭扩展活动
{

ExpandableListView explvlist;
@覆盖
公共无效的onCreate(包savedInstanceState)
{
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);

    explvlist =(ExpandableListView)findViewById(R.id.ParentLevel);
    explvlist.setAdapter(新ParentLevel());

}

公共类ParentLevel扩展BaseExpandableListAdapter
{

      @覆盖
      公共对象getChild(INT为arg0,INT ARG1)
      {
       返回ARG1;
      }

      @覆盖
      众长getChildId(INT groupPosition,INT childPosition)
      {
       返回childPosition;
      }

      @覆盖
      公共查看getChildView(INT groupPosition,诠释childPosition,布尔isLastChild,查看convertView,父母的ViewGroup)
      {
       CustExpListview SecondLevelexplv =新CustExpListview(Home.this);
       SecondLevelexplv.setAdapter(新SecondLevelAdapter());
       SecondLevelexplv.setGroupIndicator(空);
       返回SecondLevelexplv;
      }

      @覆盖
      公众诠释getChildrenCount(INT groupPosition)
      {
       返回3;
      }

      @覆盖
      公共对象getGroup(INT groupPosition)
      {
       返回groupPosition;
      }

      @覆盖
      公众诠释getGroupCount()
      {
       返回5;
      }

      @覆盖
      众长getGroupId(INT groupPosition)
      {
       返回groupPosition;
      }

      @覆盖
      公共查看getGroupView(INT groupPosition,布尔isExpanded,
        查看convertView,父母的ViewGroup)
      {
       TextView的电视=新的TextView(Home.this);
       tv.setText( - > FirstLevel);
       tv.setBackgroundColor(Color.BLUE);
       tv.setPadding(10,7,7,7);

       返回电视;
      }

  @覆盖
  公共布尔hasStableIds()
  {
   返回true;
  }

    @覆盖
  公共布尔isChildSelectable(INT groupPosition,INT childPosition)
  {
   返回true;
  }
}

公共类CustExpListview扩展ExpandableListView
{

    INT intGroupPosition,intChildPosition,intGroupid;

      公共CustExpListview(上下文的背景下)
      {
       超(上下文);
      }

      保护无效onMeasure(INT widthMeasureSpec,INT heightMeasureSpec)
      {
       widthMeasureSpec = MeasureSpec.makeMeasureSpec(960,MeasureSpec.AT_MOST);
       heightMeasureSpec = MeasureSpec.makeMeasureSpec(600,MeasureSpec.AT_MOST);
       super.onMeasure(widthMeasureSpec,heightMeasureSpec);
      }
}

公共类SecondLevelAdapter扩展BaseExpandableListAdapter
{

  @覆盖
  公共对象getChild(INT groupPosition,INT childPosition)
  {
    返回childPosition;
  }

  @覆盖
  众长getChildId(INT groupPosition,INT childPosition)
  {
    返回childPosition;
  }

  @覆盖
  公共查看getChildView(INT groupPosition,INT childPosition,
    布尔isLastChild,查看convertView,父母的ViewGroup)
  {
    TextView的电视=新的TextView(Home.this);
    tv.setText(子);
    tv.setPadding(15,5,5,5);
    tv.setBackgroundColor(Color.YELLOW);
    tv.setLayoutParams(新ListView.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
    返回电视;
  }

  @覆盖
  公众诠释getChildrenCount(INT groupPosition)
  {
    返回5;
  }

  @覆盖
  公共对象getGroup(INT groupPosition)
  {
    返回groupPosition;
  }

  @覆盖
  公众诠释getGroupCount()
  {
    返回1;
  }

  @覆盖
  众长getGroupId(INT groupPosition)
  {
    返回groupPosition;
  }

  @覆盖
  公共查看getGroupView(INT groupPosition,布尔isExpanded,查看convertView,父母的ViewGroup)
  {
       TextView的电视=新的TextView(Home.this);
       tv.setText( - >第二个等级);
       tv.setPadding(12,7,7,7);
       tv.setBackgroundColor(Color.RED);
       返回电视;
  }

@覆盖
公共布尔hasStableIds()
{
    // TODO自动生成方法存根
    返回true;
}

@覆盖
公共布尔isChildSelectable(INT groupPosition,INT childPosition)
{
    // TODO自动生成方法存根
    返回true;
}

}
}
 

I want to add one more level of in ExpandableListView.In current ExpandableListView is two level how can i add one more level. I am new in android developing please help me. Thanks in advance!

My MainActivity.java:-

 private Toolbar mToolbar;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;

//   private FragmentDrawer drawerFragment;
ArrayList<String> arraylist1,arraylist2,arraylist3,arrayList4,arrayList5;
int cnt = 0;

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

    mToolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    expListView = (ExpandableListView) findViewById(R.id.lvExp);

    // preparing list data
    prepareListData();

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

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

   /*      drawerFragment = (FragmentDrawer)
            getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
    drawerFragment.setDrawerListener(this);*/
    // display the first navigation drawer view on app launch
  //      displayView(0);
    Log.d("oncreate method", "");
    arraylist1  = new ArrayList<String>();
    arraylist2  = new ArrayList<String>();
    arraylist3  = new ArrayList<String>();
    arrayList4 =  new ArrayList<String>();
    arrayList5 =  new ArrayList<String>();
    new ProductsAsynTask().execute("http://opencart.codeniques.com/shopping/?route=feed/web_api/menu&key=test123$");


}
private void prepareListData() {
    listDataHeader = new ArrayList<String>();
    listDataChild = new HashMap<String, List<String>>();


    // Adding child data
    listDataHeader.add("Top 250");
    listDataHeader.add("Now Showing");
    listDataHeader.add("Coming Soon..");

    // Adding child data
    List<String> top250 = new ArrayList<String>();
    top250.add("The Shawshank Redemption");
    top250.add("The Godfather");
    top250.add("The Godfather: Part II");
    top250.add("Pulp Fiction");
    top250.add("The Good, the Bad and the Ugly");
    top250.add("The Dark Knight");
    top250.add("12 Angry Men");

    List<String> nowShowing = new ArrayList<String>();
    nowShowing.add("The Conjuring");
    nowShowing.add("Despicable Me 2");
    nowShowing.add("Turbo");
    nowShowing.add("Grown Ups 2");
    nowShowing.add("Red 2");
    nowShowing.add("The Wolverine");

    List<String> comingSoon = new ArrayList<String>();
    comingSoon.add("2 Guns");
    comingSoon.add("The Smurfs 2");
    comingSoon.add("The Spectacular Now");
    comingSoon.add("The Canyons");
    comingSoon.add("Europa Report");

    listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
    listDataChild.put(listDataHeader.get(1), nowShowing);
    listDataChild.put(listDataHeader.get(2), comingSoon);
}

public class ProductsAsynTask extends AsyncTask<String,Void,Void>{

    ProgressDialog dialog;

    protected void onPreExecute(){
        super.onPreExecute();
        Log.d("In onPreExceute","");
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading, Please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);
    }

    protected Void doInBackground(String... param){
        try{
            Log.d("In doInBackground","");

            HttpClient client= new DefaultHttpClient();
            HttpPost post = new HttpPost(param[0]);
            HttpResponse response = client.execute(post);

            int status = response.getStatusLine().getStatusCode();

            if(status == 200){
                Log.d("Status",""+status);

                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONObject jsonObject = new JSONObject(data);
                JSONArray jArray = jsonObject.getJSONArray("categories");

                for(int i = 0;i < jArray.length();i++){
                    cnt++;
                    Log.d("value of array",jArray.length()+"");
                    Log.d("Value of i",""+i);

                    JSONObject jsonObject1 = jArray.getJSONObject(i);


                    arraylist1.add(jsonObject1.getString("name"));
                    //data1 = jsonObject1.getString("name");
              //      Log.d("hello ",data1);

                    JSONArray jsonArray = jsonObject1.getJSONArray("children");
         //           JSONObject jsonObject2 = jsonObject1.getJSONObject("children");

                    for(int j=0;j<jsonArray.length();j++){

                        JSONObject jsonObject2 = jsonArray.getJSONObject(j);

                        arraylist2.add(jsonObject2.getString("name"));
                      //  data2 = jsonObject2.getString("name");
                        JSONArray jsonArray1 = jsonObject2.getJSONArray("children_lv3");

                        for(int k=0;k<jsonArray1.length();k++){
                            JSONObject jsonObject3 = jsonArray1.getJSONObject(k);

                            arraylist3.add(jsonObject3.getString("name"));
                            arrayList4.add(jsonObject3.getString("href"));
                           /*  data3 = jsonObject3.getString("name");
                             data4 = jsonObject3.getString("href");   */
                        }
                        arrayList5.add(jsonObject2.getString("href"));
                      // data5 = jsonObject2.getString("href");
                    }
                }

            }
        }catch(IOException e){
            Log.e("Error IOException :",e.getMessage());
        }catch (JSONException e){
            Log.e("Error JSONException",e.getMessage());
        }
            return null;
    }

    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        dialog.dismiss();
        Log.d("Counter value",""+cnt);
    }
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    if(id == R.id.action_search){
        Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}


 /*  public void onDrawerItemSelected(View view, int position) {
    displayView(position);
}

private void displayView(int position) {
    Fragment fragment = null;
    String title = getString(R.string.app_name);
    switch (position) {
        case 0:

           fragment = new HomeFragment();
           title = getString(R.string.title_home);
            break;
        case 1:
            fragment = new FriendsFragment();
            title = getString(R.string.title_friends);
            break;
        case 2:
            fragment = new MessagesFragment();
            title = getString(R.string.title_messages);
            break;
        default:
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, fragment);
        fragmentTransaction.commit();

        // set the toolbar title
        getSupportActionBar().setTitle(title);
    }
}*/}

My ExpandableListAdapter.java is here:-

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

My activity_main.xml is here:-

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


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

    <LinearLayout
        android:id="@+id/container_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar" />


    </LinearLayout>

    <FrameLayout
        android:id="@+id/container_body"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />




</LinearLayout>

<ExpandableListView
    android:id="@+id/lvExp"
    android:layout_height="match_parent"
    android:layout_width="260dp"
    android:layout_gravity="start"/>
    <!-- <fragment
    android:id="@+id/fragment_navigation_drawer"
    android:name="com.android.ShoppingMazza.activity.ExpandableListAdapter"
    android:layout_width="@dimen/nav_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:layout="@layout/fragment_navigation_drawer"
    tools:layout="@layout/fragment_navigation_drawer" /> -->
  </android.support.v4.widget.DrawerLayout>
解决方案

activity_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:layout_width="fill_parent"
     android:id="@+id/ParentLevel"
     android:groupIndicator="@null"
     android:layout_height="fill_parent">
    </ExpandableListView>

</LinearLayout>

MainActivity.Java

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;

import android.widget.TextView;

import android.widget.LinearLayout.LayoutParams;


public class Home extends Activity
{

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

    explvlist = (ExpandableListView)findViewById(R.id.ParentLevel);
    explvlist.setAdapter(new ParentLevel());

}

public class ParentLevel extends BaseExpandableListAdapter
{

      @Override
      public Object getChild(int arg0, int arg1)
      {
       return arg1;
      }

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

      @Override
      public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent)
      {
       CustExpListview SecondLevelexplv = new CustExpListview(Home.this);
       SecondLevelexplv.setAdapter(new SecondLevelAdapter());
       SecondLevelexplv.setGroupIndicator(null);
       return SecondLevelexplv;
      }

      @Override
      public int getChildrenCount(int groupPosition)
      {
       return 3;
      }

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

      @Override
      public int getGroupCount()
      {
       return 5;
      }

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

      @Override
      public View getGroupView(int groupPosition, boolean isExpanded,
        View convertView, ViewGroup parent)
      {
       TextView tv = new TextView(Home.this);
       tv.setText("->FirstLevel");
       tv.setBackgroundColor(Color.BLUE);
       tv.setPadding(10, 7, 7, 7);

       return tv;
      }

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

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

public class CustExpListview extends ExpandableListView
{

    int intGroupPosition, intChildPosition, intGroupid;

      public CustExpListview(Context context)
      {
       super(context);
      }

      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
      {
       widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.AT_MOST);
       heightMeasureSpec = MeasureSpec.makeMeasureSpec(600, MeasureSpec.AT_MOST);
       super.onMeasure(widthMeasureSpec, heightMeasureSpec);
      }
}

public class SecondLevelAdapter extends BaseExpandableListAdapter
{

  @Override
  public Object getChild(int groupPosition, int childPosition)
  {
    return childPosition;
  }

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

  @Override
  public View getChildView(int groupPosition, int childPosition,
    boolean isLastChild, View convertView, ViewGroup parent)
  {
    TextView tv = new TextView(Home.this);
    tv.setText("child");
    tv.setPadding(15, 5, 5, 5);
    tv.setBackgroundColor(Color.YELLOW);
    tv.setLayoutParams(new ListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    return tv;
  }

  @Override
  public int getChildrenCount(int groupPosition)
  {
    return 5;
  }

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

  @Override
  public int getGroupCount()
  {
    return 1;
  }

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

  @Override
  public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
  {
       TextView tv = new TextView(Home.this);
       tv.setText("-->Second Level");
       tv.setPadding(12, 7, 7, 7);
       tv.setBackgroundColor(Color.RED);
       return tv;
  }

@Override
public boolean hasStableIds()
{
    // TODO Auto-generated method stub
    return true;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
    // TODO Auto-generated method stub
    return true;
}

}
}

这篇关于如何添加三个级别的ListView在ExpandableListView在安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 23:17