Android中的列表树形展示,AndroidTreeView的使用动态设置树形结构

1、在项目中用到了这个控件【展示并选择某公司的部门】,但是在使用过程中又出一个问题——我并不知道该公司有几个部门,部门下面是否有子部门?

2、实现步骤如下:【开发工具:Android studio】

① 在项目中添加依赖:compile 'com.github.bmelnychuk:atv:1.2.+'   【是GitHub上的一个框架,搜索AndroidTreeView】

② 跟着GitHub上的介绍来做就可以了【如果是已知的部门结构的话,照着GitHub上写就能完成了,问题:不知道多少部门,不知道到部门层级】

③ 具体代码如下:【注意看注释,会有你想要的】

public class JoinDepartmentActivity extends AppCompatActivity implements
        JoinDepartmentCallView, LoadBackShowLayout.OnLoadErrorReload {
    @BindView(R.id.pcenter_toolb)
    Toolbar pcenterToolb;
    @BindView(R.id.contentView)
    RelativeLayout contentView;
    private Unbinder unbinder;
    private RegisterMResult.RegisterListBean bean;
    private JoinDepartmentPresenter presenter;
    private List dataList;
    private TreeNode root;
    private TreeNode parent;
    private TreeNode temp;
    private ArrayList departmentIdList;
    private ArrayList departmentNameList;
    private final int AUDYES = 1;
    private String departmentString = "";
    private int level = 0;
    private int RESULT_CODE = 0x3333;
    private ProgressDialog dialog;
    private LoadBackShowLayout showLayout;
    private LinearLayout.LayoutParams params;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EApplication.addActivities(this);
        setContentView(R.layout.activity_join_department);
        unbinder = ButterKnife.bind(this);
        setToolbar();
        initView();
        initData();
    }

    private void initView() {
        showLayout = new LoadBackShowLayout(this, contentView, this);
    }

    private void setToolbar() {
        setSupportActionBar(pcenterToolb);
    }

    private void initData() {
        departmentIdList = new ArrayList<>();
        departmentNameList = new ArrayList<>();
        dataList = new ArrayList<>();
        /** 这个在下面的节点holder中会使用 */
        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);


        Intent intent = this.getIntent();
        if (intent == null) return;
        bean = (RegisterMResult.RegisterListBean) intent.getSerializableExtra("data");
        /** 创建树根节点——不会显示,从第一个节点开始显示 */
        root = TreeNode.root();
        /** 第一个节点是parent */
        parent = new TreeNode(new DepartmentResult.DepartmentListBean("0", bean.getCompanyName(), 1)).setViewHolder(new MyHolder(this, 0));
        /** 将第一个节点添加进根节点 */
        root.addChild(parent);
        /** 生成树形布局视图 */
        AndroidTreeView tView = new AndroidTreeView(this, root);
        /** 将树形结构布局视图添加到布局中 */
        contentView.addView(tView.getView());
        if (bean == null) return;
        presenter = new JoinDepartmentPresenter(this);
        dialog = ProgressDialog.show(this, "", "加载中...", true);
        loadData();
    }

    private void loadData() {
        presenter.getDepartmentSonList(this, "", parent, level);
    }

    @OnClick({R.id.toolbar_back, R.id.pc_child_toolbar_subtitle, R.id.pc_child_toolbar_searchbtn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.pc_child_toolbar_subtitle:
                finish();
                break;
            case R.id.pc_child_toolbar_searchbtn:
                showDialog();
                break;
        }
    }

    //加入部门弹出框
    private void showDialog() {
        departmentString = "";
        if (departmentIdList.size() == 0) {
            departmentIdList.add(bean.getCompanyId());
            departmentNameList.add(bean.getCompanyName());
        }
        for (int i = 0; i < departmentNameList.size(); i++) {
            if (i < departmentNameList.size() - 1)
                departmentString += departmentNameList.get(i) + ",";
            else departmentString += departmentNameList.get(i);
        }
        new AlertDialog.Builder(this)
                .setTitle("系统提示")
                .setMessage("确定将【" + bean.getRealname() + "】加入以下部门?\n" + departmentString.trim())
                .setNegativeButton("取消", null)
                .setPositiveButton("确定加入", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        presenter.audRegisterUser(JoinDepartmentActivity.this, bean.getRegId(), AUDYES, null, departmentIdList);
                    }
                }).setCancelable(true).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null) unbinder.unbind();
        if (presenter != null) presenter.setCallViewNull(this);
    }

    //-------------------------------------回调开始-------------------------------
    @Override
    public void loadStart() {//开始起查询部门
        if (!dialog.isShowing()) dialog.onStart();
    }

    @Override
    public void getDepartmentListFailure(String msg) {
        if (dialog.isShowing()) dialog.dismiss();
        Toast.makeText(this, "获取部门失败," + msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * @param result 返回结果
     * @param node 父节点
     * @param level 层级
     */
    @Override
    public void getDepartmentListSuccess(DepartmentResult result, TreeNode node, int level) {
        dataList.clear();
        if (result != null && result.getDepartmentList() != null && result.getDepartmentList().size() > 0) {
            dataList.addAll(result.getDepartmentList());
        }
        for (int i = 0; i < dataList.size(); i++) {
            temp = new TreeNode(dataList.get(i)).setViewHolder(new MyHolder(this, (level + 1)));
            /** 将得到的子节点添加到父节点——参数传过来的节点 */
            node.addChild(temp);
            /** 判断有子部门则继续请求 */
            if (dataList.get(i).getSubCount() > 0)
                presenter.getDepartmentSonList(this, dataList.get(i).getDepartmentId(), temp, (level + 1));
        }
        if (dialog.isShowing()) dialog.dismiss();
    }

    @Override
    public void joinSuccess() {
        showLayout.showOnloadOk();
        Toast.makeText(this, "已成功将该人员加入部门", Toast.LENGTH_SHORT).show();
        setResult(RESULT_CODE);
        this.finish();
    }

    @Override
    public void joinFailure(String msg) {
        Toast.makeText(this, "加入部门失败," + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void loadErrorMsg(String msg) {
        showLayout.showOnError(msg);
    }

    @Override
    public void reLoad() {
        level = 0;
        loadData();
    }
    //-------------------------------------回调结束-------------------------------

    /**
     * 自定义节点视图的holder类
     */
    class MyHolder extends TreeNode.BaseNodeViewHolder {
        private int level;//表示层级
        private boolean isExpand = false;
        private DepartmentResult.DepartmentListBean bean;

        public MyHolder(Context context, int level) {
            super(context);
            this.level = level;
        }

        @Override
        public View createNodeView(final TreeNode node, final DepartmentResult.DepartmentListBean value) {
            this.bean = value;
            final LayoutInflater inflater = LayoutInflater.from(context);
            final View view = inflater.inflate(R.layout.item_only_text, null, false);
            /** 设置节点的布局,使其宽度——martch_parent,高度——wrap_content */
            view.setLayoutParams(params);
            /** 根据层级来设置左边的缩进 */
            view.setPadding(level * 50, view.getPaddingTop(), view.getRight(), view.getPaddingBottom());
            TextView tvValue = (TextView) view.findViewById(R.id.only_text);
            final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
            final CheckBox checkBoxRight = (CheckBox) view.findViewById(R.id.checkbox_right);
            if (value.getSubCount() > 0) {
                checkBoxRight.setVisibility(View.VISIBLE);
            } else {
                checkBoxRight.setVisibility(View.GONE);
            }
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        //选中则添加
                        departmentIdList.add(value.getDepartmentId());
                        departmentNameList.add(value.getName());
                    } else {
                        //取消选中则移除
                        departmentIdList.remove(value.getDepartmentId());
                        departmentNameList.remove(value.getName());
                    }
                }
            });
            node.setClickListener(new TreeNode.TreeNodeClickListener() {
                @Override
                public void onClick(TreeNode node, Object value) {
                    if (isExpand) {
                        checkBoxRight.setBackgroundResource(R.drawable.arrow_right_gray);
                        isExpand = false;
                        /** 没有子部门点击整列(即:点击节点)选中该部门 */
                        if (bean.getSubCount() == 0) {
                            checkBox.setChecked(false);
                        }
                    } else {
                        checkBoxRight.setBackgroundResource(R.drawable.arrow_down_gray);
                        isExpand = true;
                        if (bean.getSubCount() == 0) {
                            checkBox.setChecked(true);
                        }
                    }

                }
            });
            tvValue.setText(value.getName());
            return view;
        }
    }
}

④ 代码执行过程:进入该Activity添加根节点,根节点添加parent节点【公司】,得到parent下面的子部门,判断子部门下还有子部门则继续请求,没有则不请求。

开始请求就弹出“加载中..”的progressdialog【cancelable=false】,返回则取消,直到最后一次返回才dialog消失。这个时候可以点节点点出子级部门

⑤ 下面节点布局



    
    
    
 ⑥ 下面是Activity布局




    
        
            
            
            
            
        
    
    
    






你可能感兴趣的:(Android基础)