1. 程式人生 > 其它 >Android Studio 二級樹形列表---2(封裝)---補充

Android Studio 二級樹形列表---2(封裝)---補充

上一篇已經將二級樹形列表做了封裝,如果直接使用的話,看上去是沒有任何問題了,但是bug還是有的,比如一級選單下面沒有子欄目的話,點選會出現app閃退現象。這個就是個很大的缺陷,在加上實現操作中不僅僅是簡單的列表展示,還會有動態新增一個父節點,或者動態新增一個子節點,動態刪除一個節點,又或者動態刪除一個子節點。這些都是必須的。

所以接下來我要把這些都要補充進去,這樣用起來就基本滿足一般的需求了。

首先是LayerAdapterInterface介面:

package com.example.appview.Common.TwoTree;

import android.view.View;
import android.view.ViewGroup;

public interface LayerAdapterInterface { /** * * @param groupPosition 第一層位置 * @param convertView 第一層檢視 * @return */ public View getGroupView(int groupPosition, View convertView); /** * * @param groupPosition 第一層組位置 * @param childPosition 第二層view位置 * @param convertView 第二層檢視 * @return
*/ public View getChildView(int groupPosition, int childPosition, View convertView); }

接下來是通用類的封裝:

package com.example.appview.Common.TwoTree;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.appview.Demo;
import com.example.appview.mian_page.Frament.Preject_Tance_Frament.ItemA_Model.ThreeTreeModel;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/* _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 永無BUG */ public class LayerAdapterHelper<T1,T2,TControl extends LayerAdapterInterface> extends BaseExpandableListAdapter { public List<T1> oneTree; //二級列表第一層 public List<List<T2>> twoTree;//二級列表第二層 private TControl tControl; //這個是我們初始化控制元件用的類,這個是每一個Activity頁面獨有的,因為每個佈局裡面的內容可能不一樣。 private int RoneTree;//這個是二級列表第一層的頁面佈局 R.layout.佈局頁面 private int RtwoTree;//這個是二級列表第二層的頁面佈局 R.layout.佈局頁面 private Context context; LayoutInflater layoutInflater; public LayerAdapterHelper(Context context,List<T1> oneTree, List<List<T2>> twoTree,TControl tControl,int RoneTree,int RtwoTree){ this.context=context; this.oneTree=oneTree; this.twoTree=twoTree; this.tControl=tControl; this.RoneTree=RoneTree; this.RtwoTree=RtwoTree; layoutInflater = LayoutInflater.from(context); } //保證每次只展開一組 public void OnlyOne(ExpandableListView expandableListView){ expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener(){ @Override public void onGroupExpand(int groupPosition) { //保證每次只展開一組 int count=expandableListView.getExpandableListAdapter().getGroupCount(); for(int i=0;i<count; i++){ if(groupPosition != i){ expandableListView.collapseGroup(i); } } } }); } // 這裡是控制如果列表沒有孩子選單不展開的效果 public void IsChildenCount(ExpandableListView expandableListView){ expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // TODO Auto-generated method stub if (twoTree.get(groupPosition)==null) {// isEmpty沒有 Toast.makeText(context, "你點選了~" + groupPosition + "~項", Toast.LENGTH_SHORT).show(); return true; } else { return false; } } }); } //向第一層樹形中新增一個元素 public void add(int groupPosition,T1 t) { if (oneTree == null) { oneTree= new ArrayList<>(); } oneTree.add(groupPosition,t); twoTree.add(groupPosition,null); notifyDataSetChanged(); } //向第二層樹形中新增一個元素 public void addItem(int groupPosition, T2 t) { if (twoTree.get(groupPosition) == null) { Toast.makeText(context, "你點選了~" + groupPosition + "~項", Toast.LENGTH_SHORT).show(); List<T2> list=new ArrayList<>(); list.add(t); twoTree.set(groupPosition,list); }else{ twoTree.get(groupPosition).add(t); } notifyDataSetChanged(); } //向第一層樹形中特定位置移除一個元素 public void remove(int position) { if (oneTree != null) { oneTree.remove(position); } notifyDataSetChanged(); } //向第二層樹形中特定位置移除一個元素 public void remove(int groupPosition,int childPosition) { if (twoTree.get(groupPosition).get(childPosition)!=null) { twoTree.get(groupPosition).remove(childPosition); } notifyDataSetChanged(); } //組數量 @Override public int getGroupCount() { return oneTree.size(); } //子View數量 @Override public int getChildrenCount(int groupPosition) { return twoTree.get(groupPosition).size(); } //獲取組物件 @Override public Object getGroup(int groupPosition) { return oneTree.get(groupPosition); } //獲取子View物件 @Override public Object getChild(int groupPosition, int childPosition) { return twoTree.get(groupPosition).get(childPosition); } // 組View下標 @Override public long getGroupId(int groupPosition) { return groupPosition; } //子View下標 @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return false; } //取得用於顯示給定分組的檢視. 這個方法僅返回分組的檢視物件 @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { convertView= layoutInflater.inflate(RoneTree, null); return tControl.getGroupView(groupPosition,convertView); } //取得顯示給定分組給定子位置的資料用的檢視 @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { convertView= layoutInflater.inflate(RtwoTree, null); return tControl.getChildView(groupPosition,childPosition,convertView); } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } }

實現類:

package com.example.appview;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.appview.Common.TwoTree.LayerAdapterHelper;
import com.example.appview.Common.TwoTree.LayerAdapterInterface;
import com.example.appview.mian_page.Frament.Preject_Tance_Frament.ItemA_Activity.Preject_ItemA_AddCaiJi;
import com.example.appview.mian_page.Frament.Preject_Tance_Frament.ItemA_Activity.Preject_ItemA_AlterJZ;
import com.example.appview.mian_page.Frament.Preject_Tance_Frament.ItemA_Activity.Preject_Item_AddJL;
import com.example.appview.mian_page.Frament.Preject_Tance_Frament.ItemA_Model.JiLouModel;
import com.example.appview.mian_page.Frament.Preject_Tance_Frament.ItemA_Model.SheiBeiModel;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Demo extends AppCompatActivity {
    private ExpandableListView expandableListView;
    private List<JiLouModel> jiLou=new ArrayList<>();
    private List<SheiBeiModel> sheiBei;
    private List<List<SheiBeiModel>> sheiBeiModels=new ArrayList<>();
    private LayerAdapterHelper<JiLouModel,SheiBeiModel,myControl> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
       expandableListView = findViewById(R.id.expandable_listView);
        initdata();
        adapter=new LayerAdapterHelper<>(Demo.this,jiLou,sheiBeiModels,new myControl(),R.layout.preject_item_addcaiji_onetree,R.layout.preject_item_addcaiji_twotree);
        expandableListView .setAdapter(adapter);
         //保證每次只展開一組
        adapter.OnlyOne(expandableListView);
        // 這裡是控制如果列表沒有孩子選單不展開的效果
        adapter.IsChildenCount(expandableListView);
    }
    //創造資料
    public void initdata(){

        jiLou.add(new JiLouModel(1,"機樓1","",new Date(System.currentTimeMillis())));
        jiLou.add(new JiLouModel(1,"機樓2","",new Date(System.currentTimeMillis())));
        jiLou.add(new JiLouModel(1,"機樓3","",new Date(System.currentTimeMillis())));

        sheiBei=new ArrayList<>();
        sheiBei.add(new SheiBeiModel(1,"裝置1",""));
        sheiBei.add(new SheiBeiModel(1,"裝置2",""));
        sheiBei.add(new SheiBeiModel(1,"裝置3",""));

        sheiBeiModels.add(sheiBei);
        sheiBeiModels.add(null);//這個是如果父節點沒有子節點的情況下,自己新增一個null內容
        sheiBei=new ArrayList<>();
        sheiBei.add(new SheiBeiModel(1,"裝置4",""));
        sheiBei.add(new SheiBeiModel(1,"裝置5",""));
        sheiBei.add(new SheiBeiModel(1,"裝置6",""));

        sheiBeiModels.add(sheiBei);


    }
  class myControl implements LayerAdapterInterface{
      @Override
      public View getGroupView(int groupPosition, View convertView) {
          TextView textView = convertView.findViewById(R.id.preject_item_caijiqi_onetree);
          textView.setText(adapter.oneTree.get(groupPosition).getJiLouName());
          LinearLayout linearLayout=convertView.findViewById(R.id.preject_item_imagecaiji_onetree);
          linearLayout.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {

                 getOne(linearLayout,groupPosition);
              }
          });
          return convertView;
      }

      @Override
      public View getChildView(int groupPosition, int childPosition, View convertView) {
          convertView.setPadding(50,5,0,5);
          TextView textView = convertView.findViewById(R.id.preject_item_dianbiao);
          textView.setText(adapter.twoTree.get(groupPosition).get(childPosition).getSheBeiName());
          LinearLayout linearLayout=convertView.findViewById(R.id.preject_item_layoutcaozuo_twotree);

          linearLayout.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
            getTwo(linearLayout,groupPosition,childPosition);
              }
          });
          return convertView;
      }
  }
    private void getOne(LinearLayout linearLayout, int position){
        View popupView = View.inflate(Demo.this, R.layout.preject_item_pop_alter, null);
        Button btn1=popupView.findViewById(R.id.preject_item_alter_btn1);
        Button btn2=popupView.findViewById(R.id.preject_item_alter_btn2);
        btn1.setText("新增機樓");
        btn2.setText("刪除");
        GradientDrawable drawable1 =(GradientDrawable)btn1.getBackground();
        drawable1.setColor(getResources().getColor(R.color.preject4));
        GradientDrawable drawable2 =(GradientDrawable)btn2.getBackground();
        drawable2.setColor(getResources().getColor(R.color.preject3));
        PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(R.anim.move_pop_left_in);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        int popupWidth = popupView.getMeasuredWidth();
        int popupHeight =  popupView.getMeasuredHeight();
        int[] location = new int[2];
        linearLayout.getLocationOnScreen(location);
        popupWindow.showAtLocation(linearLayout, Gravity.NO_GRAVITY, location[0], location[1]);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

             //   adapter.add(0,new JiLouModel(1,"機樓1","",new Date(System.currentTimeMillis())));
            //
                adapter.addItem(position,new SheiBeiModel(1,"裝置4",""));
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });

    }
    private void getTwo(LinearLayout linearLayout, int position,int childenPosition){
        View popupView = View.inflate(Demo.this, R.layout.preject_item_pop_alter, null);
        Button btn1=popupView.findViewById(R.id.preject_item_alter_btn1);
        Button btn2=popupView.findViewById(R.id.preject_item_alter_btn2);
        btn1.setText("新增機樓");
        btn2.setText("刪除");
        btn1.setVisibility(btn1.GONE);
        GradientDrawable drawable1 =(GradientDrawable)btn1.getBackground();
        drawable1.setColor(getResources().getColor(R.color.preject4));
        GradientDrawable drawable2 =(GradientDrawable)btn2.getBackground();
        drawable2.setColor(getResources().getColor(R.color.preject3));
        PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(R.anim.move_pop_left_in);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        int popupWidth = popupView.getMeasuredWidth();
        int popupHeight =  popupView.getMeasuredHeight();
        int[] location = new int[2];
        linearLayout.getLocationOnScreen(location);
        popupWindow.showAtLocation(linearLayout, Gravity.NO_GRAVITY, location[0], location[1]);

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });

    }

}

佈局頁面就不再放在去了,和上一篇一樣。

最後看一下效果圖:

.Net Core