TreeListVew+PullToRefreshListView结合使用

22 篇文章 0 订阅
11 篇文章 0 订阅

因为项目中有个管控区域的功能需要用到树形列表功能,于是在网上找了demo,看到了张鸿洋写了一个类似功能的demo,就参考一下,完成此功能,后续因为服务器数据不定时间会变化,要提供个刷新功能,以便于可以实时得到最新的数据,所以就想起能否和pulltorefreshlistview结合使用呢?做个下拉刷新,岂不是更好,然后就有研究了一下修改treelistview的部分代码完成了这个功能,对于treelistview不明白的可以去看张鸿洋博客http://blog.csdn.net/lmj623565791/article/details/40212367

pulltorefreshlistview的使用方法可以去github看https://github.com/chrisbanes/Android-PullToRefresh/tree/master/library

我把APK和源代码上传,可以安装看效果

下载地址:http://download.csdn.net/detail/csdn576038874/9853363



因为列表中需要有选中和未选中的状态的功能,所以我们添加一个TreeNodeChecked标签来标识item的选中和未选中

/**
 * @项目名: 	gdmsaec-app
 * @包名:	com.winfo.gdmsaec.app.view.tree
 * @类名:	TreeNodeChecked
 * @创建者:	wenjie
 * @创建时间:	2015-12-4	下午3:30:34 
 * @描述:	TODO
 * 
 * @svn版本:	$Rev: 601 $
 * @更新人:	$Author: wenjie $
 * @更新时间:	$Date: 2015-12-04 16:18:26 +0800 (Fri, 04 Dec 2015) $
 * @更新描述:	TODO
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TreeNodeChecked {
	
}
以下是treeview源码类,我也直接贴出来吧,

package wenjie.winfo.com.widget.treeview;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TreeNodeId
{
}

package wenjie.winfo.com.widget.treeview;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TreeNodeLabel
{

}


package wenjie.winfo.com.widget.treeview;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TreeNodePid
{

}


node类这里新增isChecked

package wenjie.winfo.com.widget.treeview;

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

/**
 * 
 * @author 00
 */
public class Node
{

	private boolean isChecked;
	
	
	
	public boolean isChecked() {
		return isChecked;
	}

	public void setChecked(boolean isChecked) {
		this.isChecked = isChecked;
	}

	private String desc;
	
	
	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	private String id;
	/**
	 * 根节点pId为0
	 */
	private String pId = 0+"";

	private String name;

	/**
	 * 当前的级别
	 */
	private int level;

	/**
	 * 是否展开
	 */
	private boolean isExpand = false;

	private int icon;

	/**
	 * 下一级的子Node
	 */
	private List<Node> children = new ArrayList<Node>();

	/**
	 * 父Node
	 */
	private Node parent;

	public Node()
	{
	}

	public Node(String id, String pId, String name,boolean isChecked)
	{
		super();
		this.id = id;
		this.pId = pId;
		this.name = name;
		this.isChecked = isChecked;
	}

	public int getIcon()
	{
		return icon;
	}

	public void setIcon(int icon)
	{
		this.icon = icon;
	}


	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getpId() {
		return pId;
	}

	public void setpId(String pId) {
		this.pId = pId;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public void setLevel(int level)
	{
		this.level = level;
	}

	public boolean isExpand()
	{
		return isExpand;
	}

	public List<Node> getChildren()
	{
		return children;
	}

	public void setChildren(List<Node> children)
	{
		this.children = children;
	}

	public Node getParent()
	{
		return parent;
	}

	public void setParent(Node parent)
	{
		this.parent = parent;
	}

	/**
	 * 是否为跟节点
	 * 
	 * @return
	 */
	public boolean isRoot()
	{
		return parent == null;
	}

	/**
	 * 判断父节点是否展开
	 * 
	 * @return
	 */
	public boolean isParentExpand()
	{
		if (parent == null)
			return false;
		return parent.isExpand();
	}

	/**
	 * 是否是叶子界点
	 * 
	 * @return
	 */
	public boolean isLeaf()
	{
		return children.size() == 0;
	}

	/**
	 * 获取level
	 */
	public int getLevel()
	{
		return parent == null ? 0 : parent.getLevel() + 1;
	}

	/**
	 * 设置展开
	 * 
	 * @param isExpand
	 */
	public void setExpand(boolean isExpand)
	{
		this.isExpand = isExpand;
		if (!isExpand)
		{

			for (Node node : children)
			{
				node.setExpand(isExpand);
			}
		}
	}
}

treeHelper类有部分参照着改动,具体看代码
package wenjie.winfo.com.widget.treeview;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import wenjie.winfo.com.R;

/**
 * 
 * @author 00
 */
public class TreeHelper
{
	/**
	 * 传入我们的普通bean,转化为我们排序后的Node
	 * 
	 * @param datas
	 * @param defaultExpandLevel
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static <T> List<Node> getSortedNodes(List<T> datas,
			int defaultExpandLevel) throws IllegalArgumentException,
			IllegalAccessException

	{
		List<Node> result = new ArrayList<Node>();
		// 将用户数据转化为List<Node>
		
		
		List<Node> nodes = convetData2Node(datas);
		// 拿到根节点
		List<Node> rootNodes = getRootNodes(nodes);
		// 排序以及设置Node间关系
		for (Node node : rootNodes)
		{
			addNode(result, node, defaultExpandLevel, 1);
		}
		return result;
	}

	/**
	 * 过滤出所有可见的Node
	 * 
	 * @param nodes
	 * @return
	 */
	public static List<Node> filterVisibleNode(List<Node> nodes)
	{
		List<Node> result = new ArrayList<Node>();

		for (Node node : nodes)
		{
			// 如果为跟节点,或者上层目录为展开状态
			if (node.isRoot() || node.isParentExpand())
			{
				setNodeIcon(node);
				result.add(node);
			}
		}
		return result;
	}

	/**
	 * 将我们的数据转化为树的节点 
	 * 我们的数据有isChecked是否被选中的属性 来回显用户之前的选择,所以在这里我们吧 数据转转成node节点数据  带上手否被选中isChecked这样的话 
	 * 我们只需要专心操作我们的数据就好了  不用再管node,node和我们的数据是关联起来的,数据变化node也会变化 
	 * 所以我们加上TreeNodeChecked注解 同id,pid和label一样 利用注解和反射将数据的isChecked的值赋值给node 
	 * @param datas
	 * @return
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	private static <T> List<Node> convetData2Node(List<T> datas)
			throws IllegalArgumentException, IllegalAccessException

	{
		List<Node> nodes = new ArrayList<Node>();
		Node node = null;

		for (T t : datas)
		{
			String id = null;
			String pId = null;
			boolean isChecked = false;
			String label = null;
			
			Class<? extends Object> clazz = t.getClass();
			Field[] declaredFields = clazz.getDeclaredFields();
			for (Field f : declaredFields)
			{
				if (f.getAnnotation(TreeNodeId.class) != null)
				{
					f.setAccessible(true);
					id = (String) f.get(t);
				}
				if (f.getAnnotation(TreeNodePid.class) != null)
				{
					f.setAccessible(true);
					pId = (String) f.get(t);
				}
				if (f.getAnnotation(TreeNodeLabel.class) != null)
				{
					f.setAccessible(true);
					label = (String) f.get(t);
				}
				if(f.getAnnotation(TreeNodeChecked.class) != null){
					f.setAccessible(true);
					isChecked = f.getBoolean(t);
				}
				if (id != null && pId != null && label != null)
				{
					break;
				}
			}
			node = new Node(id, pId, label,isChecked);
			nodes.add(node);
		}

		/**
		 * 设置Node间,父子关系;让每两个节点都比较一次,即可设置其中的关系
		 */
		for (int i = 0; i < nodes.size(); i++)
		{
			Node n = nodes.get(i);
			for (int j = i + 1; j < nodes.size(); j++)
			{
				Node m = nodes.get(j);
				if (m.getpId().equals( n.getId()))
				{
					n.getChildren().add(m);
					m.setParent(n);
				} else if (m.getId().equals(n.getpId()))
				{
					m.getChildren().add(n);
					n.setParent(m);
				}
			}
		}

		// 设置图片
		for (Node n : nodes)
		{
			setNodeIcon(n);
		}
		return nodes;
	}

	private static List<Node> getRootNodes(List<Node> nodes)
	{
		List<Node> root = new ArrayList<Node>();
		for (Node node : nodes)
		{
			if (node.isRoot())
				root.add(node);
		}
		return root;
	}

	/**
	 * 把一个节点上的所有的内容都挂上去
	 */
	private static void addNode(List<Node> nodes, Node node,
			int defaultExpandLeval, int currentLevel)
	{

		nodes.add(node);
		if (defaultExpandLeval >= currentLevel)
		{
			node.setExpand(true);
		}

		if (node.isLeaf())
			return;
		for (int i = 0; i < node.getChildren().size(); i++)
		{
			addNode(nodes, node.getChildren().get(i), defaultExpandLeval,
					currentLevel + 1);
		}
	}

	/**
	 * 设置节点的图标
	 * 
	 * @param node
	 */
	private static void setNodeIcon(Node node)
	{
		if (node.getLevel() ==0 && node.isExpand())
		{
			node.setIcon(R.mipmap.control_botom);
		} else if (node.getLevel() ==0 && !node.isExpand())
		{
			node.setIcon(R.mipmap.control_right);
		}
		else if(node.getLevel() ==1 && node.isExpand()){
			node.setIcon(R.mipmap.node_ec);
		}else if(node.getLevel() ==1 && !node.isExpand()){
			node.setIcon(R.mipmap.node_ex);
		}
		else
			node.setIcon(R.mipmap.control_dec);
	}

}


TreeListViewAdapter

package wenjie.winfo.com.widget.treeview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;

import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.List;

/**
 * 
 * @author 00
 *
 * @param <T>
 */
public abstract class TreeListViewAdapter<T>  extends BaseAdapter
{
	protected Context mContext;
	/**
	 * 存储所有可见的Node
	 */
	protected List<Node> mNodes;
	protected LayoutInflater mInflater;
    protected List<T> datas;
	/**
	 * 存储所有的Node
	 */
	protected List<Node> mAllNodes;

	/**
	 * 点击的回调接口
	 */
	private OnTreeNodeClickListener onTreeNodeClickListener;

	public interface OnTreeNodeClickListener
	{
		void onClick(Node node, int position);
	}

	public void setOnTreeNodeClickListener(
			OnTreeNodeClickListener onTreeNodeClickListener)
	{
		this.onTreeNodeClickListener = onTreeNodeClickListener;
	}

	protected void referesh()throws IllegalArgumentException,IllegalAccessException{
		/**
		 * 对所有的Node进行排序
		 */
		mAllNodes = TreeHelper.getSortedNodes(datas, 0);
		/**
		 * 过滤出可见的Node
		 */
		mNodes = TreeHelper.filterVisibleNode(mAllNodes);
		notifyDataSetChanged();
	}

	/**
	 * 
	 * @param mTree
	 * @param context
	 * @param datas
	 * @param defaultExpandLevel
	 *            默认展开几级树
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public TreeListViewAdapter(PullToRefreshListView mTree, Context context, List<T> datas,
							   int defaultExpandLevel) throws IllegalArgumentException,
			IllegalAccessException
	{
		mContext = context;
		/**
		 * 对所有的Node进行排序
		 */
		mAllNodes = TreeHelper.getSortedNodes(datas, defaultExpandLevel);
		/**
		 * 过滤出可见的Node
		 */
		mNodes = TreeHelper.filterVisibleNode(mAllNodes);
		mInflater = LayoutInflater.from(context);

		/**
		 * 设置节点点击时,可以展开以及关闭;并且将ItemClick事件继续往外公布
		 */
		mTree.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				position = position - 1;
				expandOrCollapse(position);

				if (onTreeNodeClickListener != null)
				{
					onTreeNodeClickListener.onClick(mNodes.get(position),
							position);
				}
			}
		});

	}

	/**
	 * 相应ListView的点击事件 展开或关闭某节点
	 * 
	 * @param position
	 */
	private void expandOrCollapse(int position)
	{
		Node n = mNodes.get(position);

		if (n != null)// 排除传入参数错误异常
		{
			if (!n.isLeaf())
			{
				n.setExpand(!n.isExpand());
				mNodes = TreeHelper.filterVisibleNode(mAllNodes);
				notifyDataSetChanged();// 刷新视图
			}
		}
	}

	@Override
	public int getCount()
	{
		return mNodes.size();
	}

	@Override
	public Object getItem(int position)
	{
		return mNodes.get(position);
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		Node node = mNodes.get(position);
		convertView = getConvertView(node, position, convertView, parent);
		// 设置内边距
		convertView.setPadding(node.getLevel() * 30, 3, 3, 3);
		return convertView;
	}

	public abstract View getConvertView(Node node, int position,
			View convertView, ViewGroup parent);

}

数据实体类

package wenjie.winfo.com;

import java.io.Serializable;
import java.util.List;

import wenjie.winfo.com.widget.treeview.TreeNodeChecked;
import wenjie.winfo.com.widget.treeview.TreeNodeId;
import wenjie.winfo.com.widget.treeview.TreeNodeLabel;
import wenjie.winfo.com.widget.treeview.TreeNodePid;

/**
 * @项目名: gdmsaec-app
 * @包名: com.winfo.gdmsaec.app.domain.controlarea
 * @类名: ControlArea
 * @创建者: wenjie
 * @创建时间: 2015-11-18	下午1:22:01
 * @描述: 管控区域列表模型
 * @svn版本: $Rev: 1768 $
 * @更新人: $Author: wenjie $
 * @更新时间: $Date: 2016-03-22 16:42:54 +0800 (Tue, 22 Mar 2016) $
 * @更新描述: TODO
 */
public class ControlArea implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /**
     * id
     */
    @TreeNodeId
    private String id;

    /**
     * 父节点的名称
     */
    @TreeNodePid
    private String pId;

    /**
     * 显示的名称
     */
    @TreeNodeLabel
    private String text;

    /**
     * 是否被选中
     */
    @TreeNodeChecked
    private boolean isChecked;

    private List<ControlArea> children;

    public List<ControlArea> getChildren() {
        return children;
    }

    public void setChildren(List<ControlArea> children) {
        this.children = children;
    }

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean isChecked) {
        this.isChecked = isChecked;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getpId() {
        return pId;
    }

    public void setpId(String pId) {
        this.pId = pId;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}


继承TreeListViewAdapter实现适配器

package wenjie.winfo.com;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.List;

import wenjie.winfo.com.widget.treeview.Node;
import wenjie.winfo.com.widget.treeview.TreeListViewAdapter;

/**
 * 管控区域的列表适配器
 *
 * @param <T>
 * @author 00
 */
public class ControlAreaAdapter<T> extends TreeListViewAdapter<T> {

    private OnCheckBoxClickListener onCheckBoxClickListener;

    public interface OnCheckBoxClickListener {
        void onClik(String id, String lx, boolean isChecked);
    }

    public void setOnCheckBoxClickListener(OnCheckBoxClickListener onCheckBoxClickListener) {
        this.onCheckBoxClickListener = onCheckBoxClickListener;
    }

    private OnMessageClickListenner onMessageClickListenner;

    public interface OnMessageClickListenner {
        void onClik(String id, String lx);
    }

    public void setOnMessageClickListenner(OnMessageClickListenner onMessageClickListenner) {
        this.onMessageClickListenner = onMessageClickListenner;
    }

    public ControlAreaAdapter(PullToRefreshListView  mTree, Context context, List<T> datas,
                              int defaultExpandLevel) throws IllegalArgumentException,
            IllegalAccessException {
        super(mTree, context, datas, defaultExpandLevel);
    }

    @Override
    public View getConvertView(final Node node, final int position, View convertView,
                               ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.control_area_item, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.icon = (ImageView) convertView.findViewById(R.id.treenode_icon);
            viewHolder.label = (TextView) convertView.findViewById(R.id.treenode_label);
            viewHolder.ivCheckBox = (ImageView) convertView.findViewById(R.id.id_control_icon);
            viewHolder.line = convertView.findViewById(R.id.control_line);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.icon.setVisibility(View.VISIBLE);
        viewHolder.icon.setImageResource(node.getIcon());

        if (node.isChecked() && node.isLeaf()) {
            viewHolder.ivCheckBox.setVisibility(View.VISIBLE);
        } else {
            viewHolder.ivCheckBox.setVisibility(View.GONE);
        }

        if(node.isLeaf()){
            viewHolder.line.setVisibility(View.VISIBLE);
        }else{
            viewHolder.line.setVisibility(View.GONE);
        }

        /**
         * 这里需要把viewHolder.checkBox 赋值给 CheckBox 不然内部类无法访问  因为内部类访问必须为final的 而viewHolder不能是final 所以 吧他复制出来给
         * 另外一个checkbox拿来使用
         * 并且 这里我们不能用checkbox的 (setOnCheckedChangeListener)选中状态改变的监听方法
         * 因为我们需要的是  在checkbox 点击为选中的时候 才调用接口查询数据,不然在lsitView中checkbox复用时,会一直调用setOnCheckedChangeListener
         * 这个事件,只要被选中了  就会执行请求,不符合要求
         */
//		final ImageView box = viewHolder.checkBox;
//		viewHolder.checkBox.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
				boolean isChecked = box.isChecked();
				node.setChecked(isChecked);
//				try {
//					String id = node.getId();
					List<ControlArea> db_data = db.findAll(Selector.from(ControlArea.class).where(WhereBuilder.b("id", "=", id)));
					ControlArea mControlArea = db_data.get(0);
//					//把已勾选的的选项保存在ControlArea中
					mControlArea.setChecked(isChecked);
					db.update(mControlArea, WhereBuilder.b("id", "=", id), "isChecked");
//					String lx = node.getParent().getName();
//					onCheckBoxClickListener.onClik(id ,lx,true);
//					
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		});

        if (node.isLeaf()) {
            viewHolder.icon.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String id = node.getId();
                    String lx = node.getParent().getName();
                    onMessageClickListenner.onClik(id, lx);
                }
            });
        } else {
            viewHolder.icon.setOnClickListener(null);
        }

//		viewHolder.checkBox.setChecked(node.isChecked());
        //onCheckBoxClickListener1.onClik(node.getId(),node.isChecked());
        if (node.isRoot()) {
            viewHolder.label.setTextSize(16);
        } else if (node.isLeaf()) {
            viewHolder.label.setTextSize(14);
        } else {
            viewHolder.label.setTextSize(15);
        }
        viewHolder.label.setText(node.getName());

        return convertView;
    }

    private class ViewHolder {
        public ImageView ivCheckBox;
        ImageView icon;
        TextView label;
        View line;
//		CheckBox checkBox;
    }

    public void referesh(List<T> datas) throws IllegalAccessException {
        this.datas = datas;
        referesh();
    }
}


json工具

package wenjie.winfo.com;

import android.content.Context;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * json 和 实体类之间的相互转换
 * @author 00
 *
 */
public class JsonUtil {
	/**
	 * 将一个实体对象  转换成一个json字符串  提示对象中可包含集合
	 * @param t 实体类
	 * @return
	 */
	public static <T> String beanToJson(T t){
		Gson gson = new Gson();
		return gson.toJson(t);
	}
	
	/**
	 * 将一个json字符串 转换成一个实体类对象 可包含list
	 * @param json
	 * @param
	 * @return
	 */
	public static <T> T jsonToBean(String json,Class<T> class1) throws InstantiationException, IllegalAccessException{
		Gson gson = new Gson();
		T t;
		t=gson.fromJson(json, class1);
		return t;
	}
	
	/**
	 * 将json字符串转换成一个json对象
	 * @param str
	 * @return
	 */
	public static JSONObject stringToJson(String str){
		try {
			return new JSONObject(str);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	public static String getString(InputStream is){
		
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			byte[] buffer = new byte[1024];
			int len;
			while((len = is.read(buffer)) != -1){
				baos.write(buffer, 0, len);
			}
			
			byte[] byteArray = baos.toByteArray();
			//String str = new String(byteArray);
			
			return new String(byteArray,"utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "";
	}
	
	/**
	 * 从assert文件夹中读取json文件,然后转化为json对象
	 * @throws Exception 
	 */
	public static JSONObject getJsonDataFromAssets(Context context,String jsonFileName) throws Exception{
		JSONObject mJsonObj;
		StringBuilder sb = new StringBuilder();
		InputStream is = context.getAssets().open(jsonFileName);
		int len;
		byte[] buf = new byte[1024];
		while ((len = is.read(buf)) != -1){
			sb.append(new String(buf, 0, len, "UTF-8"));
		}
		is.close();
		mJsonObj = new JSONObject(sb.toString());
		return mJsonObj;
	}
	
}

Mainactivity

package wenjie.winfo.com;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateUtils;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import wenjie.winfo.com.widget.treeview.Node;
import wenjie.winfo.com.widget.treeview.TreeListViewAdapter;

public class MainActivity extends AppCompatActivity {


    /**
     * 显示数据的listview
     */
    private PullToRefreshListView controlListview;
    /**
     * 管控区域列表数据的适配器
     */
    private ControlAreaAdapter<ControlArea> treeListViewAdapter;

    private ProgressDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dialog = new ProgressDialog(this);
        dialog.setTitle("提示");
        dialog.setMessage("数据加载中...");
        dialog.show();
        // 初始化listView
        controlListview = (PullToRefreshListView) findViewById(R.id.listview_control_area);
        controlListview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);//设置只能下拉刷新
        init();//初始化
        //设置listview的点击事件
        controlListview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                //设置下拉时显示的日期和时间
                String label = DateUtils.formatDateTime(MainActivity.this, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel("最后加载时间:"+label);
//                dialog.show();
                new RefereshAsyncTask().execute("newData.json");//刷新数据
            }
        });
        new DataAsyncTask().execute("data.json");
    }


    private void init() {
        ILoadingLayout startLabels = controlListview .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新");// 刚下拉时,显示的提示
        startLabels.setRefreshingLabel("正在加载...");// 刷新时
        startLabels.setReleaseLabel("放开刷新");// 下来达到一定距离时,显示的提示
    }
    /**
     * 从assert文件夹中读取json文件,然后转化为json对象
     * @throws Exception
     */
    public JSONObject getJsonDataFromAssets(Context context, String jsonFileName) throws Exception{
        JSONObject mJsonObj;
        StringBuilder sb = new StringBuilder();
        InputStream is = context.getAssets().open(jsonFileName);
        int len;
        byte[] buf = new byte[1024];
        while ((len = is.read(buf)) != -1){
            sb.append(new String(buf, 0, len, "UTF-8"));
        }
        is.close();
        mJsonObj = new JSONObject(sb.toString());
        return mJsonObj;
    }


    /**
     * 模拟异步加载数据
     */
    private class DataAsyncTask extends AsyncTask<String ,Integer , List<ControlArea>>{

        @Override
        protected List<ControlArea> doInBackground(String... params) {
            try{
                List<ControlArea> controlAreas = new ArrayList<>();
                String jsonFileName = params[0];
                JSONObject controlAreaJosn = getJsonDataFromAssets(MainActivity.this, jsonFileName);
                int result = controlAreaJosn.getInt("result");
                if(result == 1){
                    JSONArray jsonArray = controlAreaJosn.getJSONArray("data");
                    //海事处
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject hscModel  = jsonArray.getJSONObject(i);
                        ControlArea controlArea = JsonUtil.jsonToBean(hscModel.toString(), ControlArea.class);
                        controlAreas.add(controlArea);

                        //海事处下面的类型
                        JSONArray qyJsonArray = hscModel.getJSONArray("children");
                        for (int j = 0; j < qyJsonArray.length(); j++) {
                            JSONObject qyModel = qyJsonArray.getJSONObject(j);
                            ControlArea controlArea2 = JsonUtil.jsonToBean(qyModel.toString(), ControlArea.class);
                            controlAreas.add(controlArea2);

                            //类型下面的管控区域
                            JSONArray jtJsonArray = qyModel.getJSONArray("children");
                            for (int k = 0; k < jtJsonArray.length(); k++) {
                                JSONObject jtModel = jtJsonArray.getJSONObject(k);
                                ControlArea controlArea3 = JsonUtil.jsonToBean(jtModel.toString(), ControlArea.class);
                                controlAreas.add(controlArea3);
                            }
                        }
                    }
                }
                return controlAreas;
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<ControlArea> controlAreas) {
            super.onPostExecute(controlAreas);
            if(controlAreas != null){
                dialog.dismiss();
                try {
                    treeListViewAdapter = new ControlAreaAdapter<>(controlListview, MainActivity.this, controlAreas, 0);
                    controlListview.setAdapter(treeListViewAdapter);
                    //每个item的点击事件
                    treeListViewAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {

                        @Override
                        public void onClick(Node node, int position) {
                            if (node.isLeaf()) {
                                if (node.isChecked())//取消
                                {
                                    String id = node.getId();
                                    String lx = node.getParent().getName();
                                    node.setChecked(false);
                                    treeListViewAdapter.notifyDataSetChanged();
                                    Toast.makeText(MainActivity.this , "取消选中----id="+id+"---lx="+lx , Toast.LENGTH_SHORT).show();
                                } else {//选中
                                    String id = node.getId();
                                    String lx = node.getParent().getName();
                                    node.setChecked(true);
                                    treeListViewAdapter.notifyDataSetChanged();
                                    Toast.makeText(MainActivity.this , "选中----id="+id+"---lx="+lx , Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });

                    //每个item前面的图标的点击事件
                    treeListViewAdapter.setOnMessageClickListenner(new ControlAreaAdapter.OnMessageClickListenner() {

                        @Override
                        public void onClik(String id, String lx) {
                            Toast.makeText(MainActivity.this , "id="+id+"---lx="+lx , Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 模拟异步刷新数据
     */
    private class RefereshAsyncTask extends AsyncTask<String ,Integer , List<ControlArea>>{

        @Override
        protected List<ControlArea> doInBackground(String... params) {
            try{
                List<ControlArea> controlAreas = new ArrayList<>();
                String jsonFileName = params[0];
                JSONObject controlAreaJosn = getJsonDataFromAssets(MainActivity.this, jsonFileName);
                int result = controlAreaJosn.getInt("result");
                if(result == 1){
                    JSONArray jsonArray = controlAreaJosn.getJSONArray("data");
                    //海事处
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject hscModel  = jsonArray.getJSONObject(i);
                        ControlArea controlArea = JsonUtil.jsonToBean(hscModel.toString(), ControlArea.class);
                        controlAreas.add(controlArea);

                        //海事处下面的类型
                        JSONArray qyJsonArray = hscModel.getJSONArray("children");
                        for (int j = 0; j < qyJsonArray.length(); j++) {
                            JSONObject qyModel = qyJsonArray.getJSONObject(j);
                            ControlArea controlArea2 = JsonUtil.jsonToBean(qyModel.toString(), ControlArea.class);
                            controlAreas.add(controlArea2);

                            //类型下面的管控区域
                            JSONArray jtJsonArray = qyModel.getJSONArray("children");
                            for (int k = 0; k < jtJsonArray.length(); k++) {
                                JSONObject jtModel = jtJsonArray.getJSONObject(k);
                                ControlArea controlArea3 = JsonUtil.jsonToBean(jtModel.toString(), ControlArea.class);
                                controlAreas.add(controlArea3);
                            }
                        }
                    }
                }
                return controlAreas;
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<ControlArea> controlAreas) {
            super.onPostExecute(controlAreas);
            if(controlAreas != null){
                dialog.dismiss();
                try {
                    treeListViewAdapter.referesh(controlAreas);
                    controlListview.onRefreshComplete();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值