2016-03-07 15:50:10 menglele1314 阅读数 1656

android BaseExpandableListAdapter 二级菜单适配器

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ExpandableListView
        android:id="@+id/home_a_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/ll_title"
        android:childDivider="#EEEEEE"
        android:divider="#c8c7cc"
        android:dividerHeight="1dp"
        android:gravity="center"
        android:groupIndicator="@null"
        android:listSelector="#00000000" />

</RelativeLayout>
MainActivity.java
package com.zcycjy.mobile.fragment;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;

import com.zcycjy.mobile.R;
import com.zcycjy.mobile.adapter.ExpandableAdapter;
import com.zcycjy.mobile.entity.HomeType;

/**
 * @author itps
 * 
 */
public class MainActivity extends Activity {

	// 标题
	private List<String> groupArray = new ArrayList<String>();
	// 子标题
	private List<List<HomeType>> childArray = new ArrayList<List<HomeType>>();
	private ExpandableAdapter adapters;
	private ExpandableListView expandableListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getDatas(0);
		
		initView();
	}

	private void initView() {
		expandableListView = (ExpandableListView)findViewById(R.id.home_a_list);
		adapters = new ExpandableAdapter(this, groupArray, childArray);
		expandableListView.setAdapter(adapters);

		expandableListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				HomeType ht = (HomeType) adapters.getChild(groupPosition,
						childPosition);
				return false;
			}
		});
		expandableListView
				.setOnGroupExpandListener(new OnGroupExpandListener() {

					@Override
					public void onGroupExpand(int groupPosition) {
						for (int i = 0; i < groupArray.size(); i++) {
							if (groupPosition != i) {
								expandableListView.collapseGroup(i);
							}
						}
					}
				});
	}

	private void getDatas(int type) {
		// 会计
		groupArray.add("注册会计师");
		List<HomeType> ta1 = new ArrayList<HomeType>();
		ta1.add(new HomeType("会计", "000001"));
		ta1.add(new HomeType("审计", "000002"));
		ta1.add(new HomeType("财务成本管理", "000003"));
		ta1.add(new HomeType("税法", "000004"));
		ta1.add(new HomeType("经济法", "000005"));
		ta1.add(new HomeType("公司战略与风险管理", "000006"));
		groupArray.add("高级会计职称");
		List<HomeType> ta2 = new ArrayList<HomeType>();
		ta2.add(new HomeType("高级会计实务", "000011"));
		groupArray.add("中级会计职称");
		List<HomeType> ta3 = new ArrayList<HomeType>();
		ta3.add(new HomeType("中级会计实务", "000021"));
		ta3.add(new HomeType("中级经济法", "000022"));
		ta3.add(new HomeType("中级财务管理", "000023"));

		childArray.add(ta1);
		childArray.add(ta2);
		childArray.add(ta3);
	}

}
ExpandableAdapter.java
package com.zcycjy.mobile.adapter;

import java.util.List;

import com.zcycjy.mobile.entity.HomeType;

import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class ExpandableAdapter extends BaseExpandableListAdapter {

	private List<String> groupArray;
	private List<List<HomeType>> childArray;
	private Activity activity;

	public ExpandableAdapter(Activity act, List<String> groupArray,
			List<List<HomeType>> childArray) {
		this.activity = act;
		this.groupArray = groupArray;
		this.childArray = childArray;
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return childArray.get(groupPosition).get(childPosition);
	}

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

	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		String string = childArray.get(groupPosition).get(childPosition)
				.getTypeName();
		return getGenericView(string, 1);
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		// TODO Auto-generated method stub
		return childArray == null ? 0 : childArray.get(groupPosition).size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		// TODO Auto-generated method stub
		return groupArray.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		// TODO Auto-generated method stub
		return groupArray == null ? 0 : groupArray.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		// TODO Auto-generated method stub
		return groupPosition;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		String string = groupArray.get(groupPosition);
		return getGenericView(string, 0);
	}

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

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

	/**
	 * Children 's View
	 * 
	 * @param string
	 * @return
	 */
	public TextView getGenericView(String string, int i) {
		AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		TextView text = new TextView(activity);
		text.setLayoutParams(layoutParams);
		// Center the text vertically
		text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
		// Set the text starting position
		if (i == 1) {
			text.setTextColor(Color.parseColor("#000000"));
			text.setPadding(70, 10, 0, 10);
			text.setText(string + " >>>");
		} else {
			text.setTextColor(Color.parseColor("#F39801"));
			text.setPadding(40, 20, 0, 20);
			text.setText(string + " ▼▼▼");
		}
		return text;
	}
}





2015-12-26 12:37:52 ddxxll2008 阅读数 990

在Android开发之中,经常会遇到二级的串联选择菜单,今天自己写了个Demo,实现了一下这种效果,效果图如下所示

二级串联菜单实现效果图

菜单的数据结构

实现这种串联菜单,需要自己定义数据结构。我定义了一个SecondLevelDialogData,里面包括一级菜单的名称和二级菜单的数据List,代码如下:

public class SecondLevelDialogData {
    //下拉菜单里的数据结构
    String firstname;//一级菜单名称
    List<SecondLevelDialogData> secondData;//二级菜单数据

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public List<SecondLevelDialogData> getSecondData() {
        return secondData;
    }

    public void setSecondData(List<SecondLevelDialogData> secondData) {
        this.secondData = secondData;
    }
}

二级菜单实现类

有了对应的数据结构之后,我们需要实现二级串联菜单的实现类,采用PopupWindow来显示菜单,主要是实现二级菜单显示的方法,在此方法中,对数据进行复制,并设置点击事件。代码如下:

public class SecondLevelDialog {

    private static final int FIRSTPOPUPWINDOW = 1;//一级菜单
    private static final int SECONDPOPUPWINDOW = 2;//二级菜单
    private List<SecondLevelDialogData> listData;//一级菜单数据
    private int[] selectIds;//菜单选择标识位
    private Context context;

    private ListView firstListView;//一级菜单
    private ListView secondListView;//二级菜单
    private PopupWindow popupWindow;//菜单窗口
    private PopupWindowAdapter firstPopupWindowAdapter;//一级菜单数据适配器
    private PopupWindowAdapter secondPopupWindowAdapter;//二级菜单数据适配器

    public SecondLevelDialog(Context context, List<SecondLevelDialogData> firstList) {
        this.context = context;
        this.listData = listData;
        for (int i = 0; i < this.selectIds.length; i++) {
            this.selectIds[i] = 0;
        }
    }

    public SecondLevelDialog(Context context, List<SecondLevelDialogData> listData, int[] selectIds) {
        this.context = context;
        this.listData = listData;
        this.selectIds = selectIds;
    }

    //显示下拉菜单
    public int[] show(Button button) {
        View view = LayoutInflater.from(context).inflate(R.layout.seconddialoglayout, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                true);
        popupWindow.setOutsideTouchable(true);//点击PopupWindow外部可使PopupWindow消失
        popupWindow.showAsDropDown(button);//在Button下显示
        firstListView = (ListView) view.findViewById(R.id.id_listview_first);
        secondListView = (ListView) view.findViewById(R.id.id_listview_second);
        LinearLayout backgroundLinearLayout = (LinearLayout) view.findViewById(R.id.seconddialog_background);
        //点击背景,下拉列表菜单消失
        backgroundLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissPop();
            }
        });
        //设置一级菜单数据
        firstPopupWindowAdapter = new PopupWindowAdapter(context, listData, FIRSTPOPUPWINDOW, selectIds[0]);
        firstListView.setAdapter(firstPopupWindowAdapter);
        //设置一级菜单点击事件
        firstListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(context, "一级菜单" + position + "被点击", Toast.LENGTH_SHORT).show();
                //设置二级菜单数据
                List<SecondLevelDialogData> secondList = listData.get(position).getSecondData();
                secondPopupWindowAdapter = new PopupWindowAdapter(context, secondList, SECONDPOPUPWINDOW,
                        selectIds[1]);
                secondListView.setAdapter(secondPopupWindowAdapter);
                secondListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Toast.makeText(context, "二级菜单" + position + "被点击", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        return selectIds;
    }

    //下拉菜单消失
    public void dismissPop() {
        if (popupWindow != null) {
            if (popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            popupWindow = null;
        }
    }
}

菜单适配器

在PopupWindow中,采用ListView显示菜单的数据,所以需要自定义ListView的适配器,代码如下:

public class PopupWindowAdapter extends BaseAdapter{

    private Context context;
    private List<SecondLevelDialogData> list;
    private int listPosition;//菜单级数,是第几级菜单
    private int selectPosition;//默认选取的位置

    public PopupWindowAdapter (Context context, List<SecondLevelDialogData> list, int listPosition, int selectPosition) {
        this.context = context;
        this.list = list;
        this.selectPosition = selectPosition;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.listviewitemlayout, null);
            viewHolder.textView = (TextView) convertView.findViewById(R.id.id_listview_item_tv);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.textView.setText(list.get(position).getFirstname());
        //设置选中效果
        if (selectPosition == position) {
            viewHolder.textView.setTextColor(Color.RED);
        } else {
            viewHolder.textView.setTextColor(Color.BLACK);
        }
        convertView.setTag(viewHolder);
        return convertView;
    }

    private class ViewHolder {
        TextView textView;
    }
}

布局文件

只有一个Button,点击后显示二级菜单

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="选择"/>

</LinearLayout>

主界面代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn;
    private List<SecondLevelDialogData> listData = new ArrayList<>();//下拉菜单数据
    private int[] selectIds = {0, 0};//菜单选择标识位,初始位置为0

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

        initData();

        btn = (Button) findViewById(R.id.btn_select);
        btn.setOnClickListener(this);
    }

    //初始化下拉菜单数据
    private void initData() {
        for (int i = 0; i < 50; i++) {
            SecondLevelDialogData data = new SecondLevelDialogData();
            data.setFirstname("一级菜单数据" + i);
            List<SecondLevelDialogData> secondListData = new ArrayList<>();
            for (int j = 0; j < 50; j++) {
                SecondLevelDialogData secondItem = new SecondLevelDialogData();
                secondItem.setFirstname("一级菜单" + i + "  二级菜单数据" + j);
                secondListData.add(secondItem);
            }
            data.setSecondData(secondListData);
            listData.add(data);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_select:
                selectIds = new SecondLevelDialog(MainActivity.this, listData, selectIds).show(btn);
                break;
        }
    }
}

以上,便是实现二级串联菜单的方法。

2014-01-06 18:53:23 shikun520 阅读数 123



 实现如上图所示的二级菜单:

1上面是通过两个ListView实现的,父LIstView控制子ListView,其中配置文件如下

<cn.doublemenu.com.view.CategoryList
    android:orientation="vertical" android:background="#88000000"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/categorylist"
    android:visibility="gone">
    <ImageView android:layout_height="wrap_content"
        android:layout_width="wrap_content" android:src="@drawable/trangle_indicate"
        android:layout_marginBottom="-22.0dip" android:layout_marginLeft="40.0dip" />
    <RelativeLayout android:layout_height="fill_parent"
        android:layout_width="fill_parent" android:background="@drawable/addresslist_bg"
        android:layout_marginRight="15.0dip" android:layout_marginLeft="15.0dip"
        android:layout_marginTop="15.0dip" android:layout_marginBottom="40.0dip">
        <LinearLayout android:layout_height="fill_parent"
            android:layout_width="fill_parent" android:orientation="horizontal"
            android:paddingTop="2.0dip" android:paddingLeft="1.0dip"
            android:paddingRight="1.0dip" android:paddingBottom="1.0dip">
            <ListView android:id="@+id/list_group" android:scrollbars="none"
                android:background="#00000000" android:layout_width="0.0px"
                android:layout_height="fill_parent" android:cacheColorHint="#00000000"
                android:divider="#ffbbbab7" android:dividerHeight="1.0px"
                android:layout_weight="1.0" />
            <ListView android:id="@+id/list_child" android:background="#f4f4f4"
                android:layout_width="0.0px" android:layout_height="fill_parent"
                android:cacheColorHint="#00000000" android:divider="@null"
                android:layout_weight="1.0" />
        </LinearLayout>
    </RelativeLayout>
</cn.doublemenu.com.view.CategoryList>

 2自定义的cn.doublemenu.com.view.CategoryList如下:

package cn.doublemenu.com.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cn.doublemenu.com.activity.R;
import cn.doublemenu.com.bean.Category;
import cn.doublemenu.com.db.GenericDAO;

public class CategoryList extends LinearLayout {
    private List<Category> topCategories;
    private Map<Integer, List<Category>> categoriesMap;
    private GenericDAO dao;
    private Context context;
    private Listener listener;
    private ListView groupListView;
    private ListView childListView;
    private ChildAdapter adapter;
    private int positionOut;

    public interface Listener {
        public void onSelected(Category category, Category parentCategory);

        public void onScroll(Category category);
    }

    public CategoryList(Context c, AttributeSet attrs) {
        super(c, attrs);
        dao = GenericDAO.getInstance(c);
        context = c;
    }

    public void init(final Listener listener, Category category) {
        topCategories = dao.listCategories();
        categoriesMap = new HashMap<Integer, List<Category>>();
        this.listener = listener;
        adapter = new ChildAdapter(new ArrayList<Category>());
        groupListView = (ListView) findViewById(R.id.list_group);
        childListView = (ListView) findViewById(R.id.list_child);
        groupListView.setCacheColorHint(0);
        groupListView.setAdapter(new GroupAdapter());
        childListView.setAdapter(adapter);
        List<Category> childCategoryList = getCategories(0);
        adapter.setCategoryList(childCategoryList);
        adapter.notifyDataSetChanged();
        groupListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                positionOut = position;
                List<Category> childList = getCategories(position);
                adapter.setCategoryList(childList);
                adapter.notifyDataSetChanged();
                GroupAdapter adapt = (GroupAdapter) parent.getAdapter();
                adapt.setmCurSelectPosition(position);
                adapt.notifyDataSetChanged();

            }
        });
        childListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                listener.onSelected(adapter.getCategoryList().get(position),
                        topCategories.get(positionOut));
            }
        });

    }

    private List<Category> getCategories(int groupPosition) {
        List<Category> categories = categoriesMap.get(groupPosition);
        if (categories == null) {
            Category parent = topCategories.get(groupPosition);
            categories = dao.listCategories(parent);
            categoriesMap.put(groupPosition, categories);
        }

        return categories;
    }

    private class ViewHolder {
        public ImageView imgView;
        public TextView textView;
    }

    class GroupAdapter extends BaseAdapter {
        private ViewHolder mSelectHolder;
        private int mCurSelectPosition = 0;

        public ViewHolder getmSelectHolder() {
            return mSelectHolder;
        }

        public void setmSelectHolder(ViewHolder mSelectHolder) {
            this.mSelectHolder = mSelectHolder;
        }

        public int getmCurSelectPosition() {
            return mCurSelectPosition;
        }

        public void setmCurSelectPosition(int mCurSelectPosition) {
            this.mCurSelectPosition = mCurSelectPosition;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            if (topCategories != null) {
                return topCategories.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            if (topCategories != null && topCategories.size() > position - 1) {
                return topCategories.get(position);
            } else {
                return null;
            }
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            final ViewHolder viewHolder;
            if (convertView == null) {
                LayoutInflater layoutInflater = (LayoutInflater) getContext()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                convertView = layoutInflater.inflate(
                        R.layout.address_item_layout, null);
                viewHolder = new ViewHolder();

                viewHolder.textView = (TextView) convertView
                        .findViewById(R.id.city_item_title);
                viewHolder.imgView = (ImageView) convertView
                        .findViewById(R.id.img_tag);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if (position == mCurSelectPosition) {
                convertView.setBackgroundColor(getResources().getColor(
                        R.color.address_child));
                upDateItemUi(viewHolder.imgView, true);
            } else {
                convertView.setBackgroundColor(getResources().getColor(
                        R.color.white));
                upDateItemUi(viewHolder.imgView, false);
            }
            Category category = topCategories.get(position);
            viewHolder.textView.setText(category.name);
            return convertView;
        }
    }

    private void upDateItemUi(ImageView imgView, boolean b) {
        if (b) {
            imgView.setVisibility(View.VISIBLE);
        } else {
            imgView.setVisibility(View.INVISIBLE);
        }
    }

    class ChildAdapter extends BaseAdapter {
        private List<Category> categoryList;

        public List<Category> getCategoryList() {
            return categoryList;
        }

        public void setCategoryList(List<Category> categoryList) {
            this.categoryList = categoryList;
        }

        public ChildAdapter(List<Category> childList) {
            super();
            this.categoryList = childList;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            if (categoryList != null) {
                return categoryList.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            if (categoryList != null && categoryList.size() > position - 1) {
                return categoryList.get(position);
            } else {
                return null;
            }
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view = convertView;
            if (view == null) {
                LayoutInflater layoutInflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = layoutInflater.inflate(R.layout.address_textview_layout,
                        null);
            }
            TextView cityChildTextView = (TextView) view
                    .findViewById(R.id.single_textview);
            cityChildTextView.setText(categoryList.get(position).name);
            return view;
        }
    }
}

 3两个ListView包括两个Itemlayout,其中父ListView的Item是address_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="wrap_content"
    android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:layout_alignParentTop="true">
        <ImageView android:layout_height="fill_parent"
            android:layout_width="5.0dip" android:background="#ff6600"
            android:visibility="invisible" android:id="@+id/img_tag"></ImageView>
        <TextView android:layout_height="fill_parent"
            android:layout_width="fill_parent" android:textSize="16dp"
            android:layout_marginLeft="6dp" android:layout_marginTop="9.0dip"
            android:layout_marginBottom="9.0dip" android:id="@+id/city_item_title"
            android:textColor="#505050" android:singleLine="true"
            android:ellipsize="end" />
    </LinearLayout>
</RelativeLayout>

子ListView的Item是address_textview_layout.xml 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent" android:layout_width="wrap_content"
    android:paddingTop="9.0dip" android:paddingBottom="9.0dip">
    <TextView android:id="@+id/single_textview"
        android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:layout_alignParentLeft="true" android:paddingLeft="6dp"
        android:textSize="16dip" android:singleLine="true" android:ellipsize="end"
        android:background="@null" android:textColor="#707070" />
</RelativeLayout>

 

3在程序中初始化数据通过SQLite来实现

 

package cn.doublemenu.com.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import cn.doublemenu.com.activity.R;
import cn.doublemenu.com.bean.Category;

public class GenericDAO extends SQLiteOpenHelper {
    private static Object lock = new Object();

    private static SQLiteDatabase db;
    public static final String KEY_ID = "id";
    public static final int DATABASE_VERSION = 7;
    private Context context;
    private final static String DATABASE_NAME = "category";
    private static volatile GenericDAO instance;

    private GenericDAO(Context ctx) {
        super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
        context = ctx;
    }

    /*
     * public static GenericDAO getInstance() { return
     * getInstance(ActivityManager.getCurrent()); }
     */

    public static GenericDAO getInstance(Context ctx) {
        try {
            if (instance == null) {
                synchronized (lock) {
                    if (instance == null) {
                        instance = new GenericDAO(ctx);
                        db = instance.getWritableDatabase();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }

    private void onDown() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.beginTransaction();
            Log.e("test", "onCreate execute");
            load(db, R.raw.category);
            db.setTransactionSuccessful();
        } catch (Exception ee) {
            ee.printStackTrace();
            Log.e("test", ee.toString());
        } finally {
            if (db != null) {
                db.endTransaction();
            }
        }
    }

    private void load(SQLiteDatabase db, int fileId)
            throws UnsupportedEncodingException, IOException {
        BufferedReader bufferedReader = null;
        try {
            String temp;
            InputStream in = context.getResources().openRawResource(fileId);
            bufferedReader = new BufferedReader(new InputStreamReader(in,
                    "utf-8"));
            while ((temp = bufferedReader.readLine()) != null) {
                db.execSQL(temp);
                temp = null;
            }
        } catch (Exception e) {

        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception e) {

                }
            }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            db.beginTransaction();
            db.delete("category", null, null);

            db.setTransactionSuccessful();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }

    public long insert(String table, ContentValues values) {
        long ret = db.insert(table, null, values);
        return ret;
    }

    public Category getCategory(int id) {
        return Category.get(db, id);
    }

    public List<Category> listCategories() {
        try {
            List<Category> ret = Category.list(db);
            if (ret == null || ret.isEmpty()) {
                onCreate(db);
                return Category.list(db);
            }

            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            onCreate(db);
            return Category.list(db);
        }
    }

    public List<Category> listCategories(Category category) {
        return Category.list(db, category);
    }

}

CateGory定义如下、

package cn.doublemenu.com.bean;

import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Category {
    public int id;
    public Integer pid;
    public String name;

    public static Category get(SQLiteDatabase db, int id) {
        if (id == 255) {
            Category category = new Category();
            category.pid = 0;
            category.id = 255;
            category.name = "全部分类";
            return category;
        }

        Cursor cursor = db.rawQuery("SELECT * FROM category WHERE id = " + id,
                null);
        cursor.moveToFirst();

        Category ret = toCategory(cursor);
        cursor.close();

        return ret;
    }

    public static List<Category> list(SQLiteDatabase db) {
        List<Category> ret = new ArrayList<Category>();
        Cursor cursor = null;
        try {
            ret.add(get(db, 255));

            cursor = db.rawQuery("SELECT * FROM category WHERE pid IS NULL",
                    null);

            if (cursor.moveToFirst()) {
                do {
                    ret.add(toCategory(cursor));
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {

        } finally {
            if (cursor != null) {
                try {
                    cursor.close();
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
            }
        }

        return ret;
    }

    public static List<Category> list(SQLiteDatabase db, Category parent) {
        List<Category> ret = new ArrayList<Category>();
        ret.add(parent);

        Cursor cursor = db.rawQuery(
                "SELECT id,pid,name FROM category WHERE pid = " + parent.id,
                null);

        if (cursor.moveToFirst()) {
            do {
                ret.add(toCategory(cursor));
            } while (cursor.moveToNext());
        }

        cursor.close();
        return ret;
    }

    private static Category toCategory(Cursor cursor) {
        Category category = new Category();
        category.id = cursor.getInt(0);
        category.pid = cursor.getInt(1);
        category.name = cursor.getString(2);

        return category;
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof Category && ((Category) o).id == id;
    }
}

在程序中使用二级菜单:

package cn.doublemenu.com.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import cn.doublemenu.com.bean.Category;
import cn.doublemenu.com.db.GenericDAO;
import cn.doublemenu.com.view.CategoryList;

public class MainActivity extends Activity {
    protected Category category;
    private CategoryList categoryList;
    private Button categoryButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GenericDAO.getInstance(this).getWritableDatabase();

        categoryButton = (Button) findViewById(R.id.show);
        categoryButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                boolean visible = (categoryList.getVisibility() == View.VISIBLE);
                hideList(visible);

            }
        });
        initCategoryList(255);
        

    }

    protected void initCategoryList(int cat) {

        category = GenericDAO.getInstance(this).getCategory(cat);
        categoryList = (CategoryList) findViewById(R.id.categorylist);
        categoryList.init(new CategoryList.Listener() {
            public void onSelected(Category c, Category parentCategory) {
                categoryList.setVisibility(View.GONE);

            }

            public void onScroll(Category category) {
            }
        }, category);

    }

    protected void hideList(boolean vis) {
        if (categoryList != null) {
            if (vis) {
                categoryList.setVisibility(View.GONE);
            } else {
                categoryList.setVisibility(View.VISIBLE);
            }

        }
    }
}

http://blog.csdn.net/hahahacff/article/details/8830396

2016-03-07 14:54:29 menglele1314 阅读数 11688

android 二级菜单、双ListView 仿美团、购物二级菜单

下载Demo

效果如下图,下载后直接粘贴就可以用

   

Bean.java

package com.mengle.app;

import java.util.List;

public class Bean {

	/**
	 * result : Y address :
	 * [{"name":"北京","custId":"010","area":["东城区","西城区","崇文区"
	 * ,"宣武区","延庆县"]},{"name"
	 * :"上海","custId":"021","area":["黄浦区","卢湾区","徐汇区","长宁区","静安区","其他"]}]
	 */

	private String result;
	/**
	 * name : 北京 custId : 010 area : ["东城区","西城区","崇文区","宣武区","延庆县"]
	 */

	private List<AddressEntity> address;

	public void setResult(String result) {
		this.result = result;
	}

	public void setAddress(List<AddressEntity> address) {
		this.address = address;
	}

	public String getResult() {
		return result;
	}

	public List<AddressEntity> getAddress() {
		return address;
	}

	public static class AddressEntity {
		private String name;
		private String custId;
		private List<String> area;

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

		public void setCustId(String custId) {
			this.custId = custId;
		}

		public void setArea(List<String> area) {
			this.area = area;
		}

		public String getName() {
			return name;
		}

		public String getCustId() {
			return custId;
		}

		public List<String> getArea() {
			return area;
		}
	}
}
MainActivity.java

package com.mengle.app;

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

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mengle.app.Bean.AddressEntity;

public class MainActivity extends Activity {

    private DisplayMetrics dm;
    private PopupWindow popWindow;
    private MoreAdapter moreAdapter;
    private ListView morelist;
    private TextView tv;
    private List<AddressEntity> mainList;
    private ListView mainlist;
    private MainAdapter mainAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        dm = new DisplayMetrics();
        // 取得窗口属性
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        initModle();// 添加数据
        tv = (TextView) findViewById(R.id.tv);
        tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                downPopwindow();
            }
        });
    }

    private void downPopwindow() {
        // showAsDropDown(View anchor);相对某个控件的位置(正左下方),无偏移
        // showAsDropDown(View anchor, int x, int
        // y);相对某个控件的位置,有偏移;x表示相对x轴的偏移,正表示向左,负表示向右;y表示相对y轴的偏移,正是向下,负是向上;
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_down,
                null);
        int screenHeight = dm.heightPixels * 2 / 3;
        // 这里就给具体大小的数字,要不然位置不好计算
        popWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
                screenHeight);
        // popWindow.setAnimationStyle(R.style.anim);// 淡入淡出动画
        // popWindow.setTouchable(false);// 是否响应touch事件
        popWindow.setFocusable(true);// 是否具有获取焦点的能力
        // 点击PopupWindow以外的区域,PopupWindow是否会消失。
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);

        mainlist = (ListView) contentView.findViewById(R.id.classify_mainlist);
        morelist = (ListView) contentView.findViewById(R.id.classify_morelist);

        mainAdapter = new MainAdapter(this, mainList);
        mainAdapter.setSelectItem(0);
        mainlist.setAdapter(mainAdapter);

        mainlist.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                List<String> lists = mainList.get(position).getArea();
                initAdapter(lists);
                mainAdapter.setSelectItem(position);
                mainAdapter.notifyDataSetChanged();
            }
        });
        mainlist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        // 一定要设置这个属性,否则ListView不会刷新
        initAdapter(mainList.get(0).getArea());

        morelist.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                String s = (String) moreAdapter.getItem(position);
                Toast.makeText(getApplicationContext(), s, 1).show();
                moreAdapter.setSelectItem(position);
                moreAdapter.notifyDataSetChanged();
            }
        });
        popWindow.showAsDropDown(tv);
    }

    private void initAdapter(List<String> lists) {
        moreAdapter = new MoreAdapter(this, lists);
        morelist.setAdapter(moreAdapter);
        moreAdapter.notifyDataSetChanged();
    }

    private void initModle() {
        mainList = new ArrayList<AddressEntity>();
        Gson gson = new Gson();
        String json = "{\"result\":\"Y\", \"address\":[{\"name\":\"北京\",\"custId\":\""
                + R.drawable.ic_category_1
                + "\", \"area\":[\"东城区\",\"西城区\",\"崇文区\",\"宣武区\",\"延庆县\"]},{\"name\":\"上海\", \"custId\":\""
                + R.drawable.ic_category_2
                + "\",\"area\":[\"黄浦区\",\"卢湾区\",\"徐汇区\",\"长宁区\",\"静安区\",\"其他\"]}]}";
        java.lang.reflect.Type type = new TypeToken<Bean>() {
        }.getType();
        Bean b = gson.fromJson(json, type);
        mainList.addAll(b.getAddress());
    }

}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#2A3C50"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="#FAFA00"
        android:drawableRight="@drawable/holo_light"
        android:gravity="center"
        android:text="二级列表"
        android:textSize="21sp" />

</LinearLayout>
pop_down.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ListView
        android:id="@+id/classify_mainlist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:background="#fff"
        android:cacheColorHint="#00000000"
        android:divider="#ffebebeb"
        android:dividerHeight="1px"
        android:fastScrollEnabled="true"
        android:listSelector="#00000000"
        android:scrollbars="none" />

    <ListView
        android:id="@+id/classify_morelist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:background="#fff"
        android:cacheColorHint="#00000000"
        android:divider="#ffebebeb"
        android:dividerHeight="1px"
        android:fastScrollEnabled="true"
        android:listSelector="#00000000"
        android:scrollbars="none" />

</LinearLayout>
MainAdapter.java

package com.mengle.app;

import java.util.List;

import com.mengle.app.Bean.AddressEntity;

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

public class MainAdapter extends BaseAdapter {

	private Context context;
	private List<AddressEntity> list;
	private int position = 0;
	private Holder hold;

	public MainAdapter(Context context, List<AddressEntity> list) {
		this.context = context;
		this.list = list;
	}

	public int getCount() {
		return list.size();
	}

	public Object getItem(int position) {
		return list.get(position);
	}

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

	public View getView(int arg0, View view, ViewGroup viewGroup) {

		if (view == null) {
			view = View.inflate(context, R.layout.item_mainlist, null);
			hold = new Holder(view);
			view.setTag(hold);
		} else {
			hold = (Holder) view.getTag();
		}
		hold.img.setImageResource(Integer.parseInt(list.get(arg0).getCustId()));
		hold.txt.setText(list.get(arg0).getName());
		hold.layout.setBackgroundColor(0xFFEBEBEB);
		if (arg0 == position) {
			hold.layout.setBackgroundColor(0xFFFFFFFF);
		}
		return view;
	}

	public void setSelectItem(int position) {
		this.position = position;
	}

	public int getSelectItem() {
		return position;
	}

	private static class Holder {
		LinearLayout layout;
		ImageView img;
		TextView txt;

		public Holder(View view) {
			txt = (TextView) view.findViewById(R.id.mainitem_txt);
			img = (ImageView) view.findViewById(R.id.mainitem_img);
			layout = (LinearLayout) view.findViewById(R.id.mainitem_layout);
		}
	}
}

item_mainlist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/mainitem_layout"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/mainitem_img"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:paddingLeft="10dp"
            android:src="@drawable/ic_category_2" />

        <TextView
            android:id="@+id/mainitem_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:text="热门分类"
            android:textColor="#000000"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>

MoreAdapter.java

package com.mengle.app;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MoreAdapter extends BaseAdapter {

	private Context context;
	private int position = 0;
	Holder hold;
	private List<String> lists;

	public MoreAdapter(Context context, List<String> lists) {
		this.context = context;
		this.lists = lists;
	}

	public int getCount() {
		return lists.size();
	}

	public Object getItem(int position) {
		return lists.get(position);
	}

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

	public View getView(int arg0, View view, ViewGroup viewGroup) {

		if (view == null) {
			view = View.inflate(context, R.layout.item_morelist, null);
			hold = new Holder(view);
			view.setTag(hold);
		} else {
			hold = (Holder) view.getTag();
		}
		hold.txt.setText(lists.get(arg0).toString());
		hold.txt.setTextColor(0xFF666666);
		if (arg0 == position) {
			hold.txt.setTextColor(0xFFFF8C00);
		}
		return view;
	}

	public void setSelectItem(int position) {
		this.position = position;
	}

	private static class Holder {
		TextView txt;

		public Holder(View view) {
			txt = (TextView) view.findViewById(R.id.moreitem_txt);
		}
	}
}
item_morelist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:background="#ffffffff"
    android:orientation="vertical"
    android:paddingLeft="10dp" >

    <TextView
        android:id="@+id/moreitem_txt"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:gravity="center_vertical"
        android:text="全部分类"
        android:textColor="#666666"
        android:textSize="17sp" />

</LinearLayout>

2014-03-10 18:27:38 u013352090 阅读数 3162

公司项目里的需求,商城的左下角,要求有分类的Menu。

看图:

Menu效果图

1.当点击一级分类,修改二级菜单里面的内容。

2.同时一级菜单里的背景变为右边有白色三角的背景。

3.当点击二级菜单的条目时候,Popupwindow消失,并且界面更新对应条目的商品数据。

我的实现思路是:左下角弹出Popupwindow,里面使用两个ListView实现。

我的Demo的效果:

双ListView效果

1,点击一级菜单分类,修改二级菜单里面的内容:

listView.setOnItemClickListener(new OnItemClickListener() {

            @Override 
            public void onItemClick(AdapterView<?> arg0, View arg1, 
                    int position, long arg3) { 
                final int location = position; 
                myAdapter.setSelectedPosition(position);//adapter中的方法,将当前点击位置,告诉adapter。adapter根据position设置响应位置的数据。 
                myAdapter.notifyDataSetInvalidated(); 
                subAdapter = new SubAdapter(MenuPop.this.context, cities, 
                        images, position); 
                subListView.setAdapter(subAdapter); 
                subListView.setOnItemClickListener(new OnItemClickListener() {//二级菜单,根据一级菜单数据修改。

                    @Override 
                    public void onItemClick(AdapterView<?> arg0, View arg1, 
                            int position, long arg3) { 
                        Toast.makeText(MenuPop.this.context, 
                                cities[location][position], Toast.LENGTH_SHORT) 
                                .show(); 
                    } 
                }); 
            } 
        });

2,adapter中数据设置

// 设置选中效果(改变背景图片) 
        if (selectedPosition == position) { 
            holder.textView.setTextColor(Color.BLUE); 
            holder.layout.setBackgroundResource(R.drawable.fenlei_blue_on); 
        } else { 
            holder.textView.setTextColor(Color.WHITE); 
            holder.layout.setBackgroundColor(Color.TRANSPARENT); 
        }

 

//设置数据,数据现在是固定在String数组中

if (position == 0) { 
            holder.imageView.setBackgroundResource(R.color.transparent); 
        } else if (position == 1) { 
            holder.imageView.setBackgroundResource(R.color.transparent);

        } else { 
            holder.imageView.setBackgroundResource(images[position]);

        }

3,产生Popupwindow的类,通过new该对象,得到新的Popupwindow。

//构造方法中,传入当前上下文,初始化双ListView布局,设置adapter。

public MenuPop(Context context, SecondFragmentCallback callback) { 
        super(); 
        this.context = context; 
        this.callback = callback;

        View view = LayoutInflater.from(context) 
                .inflate(R.layout.popmenu, null);

        // 设置listview 
        listView = (MyListView) view.findViewById(R.id.listView); 
        subListView = (MyListView) view.findViewById(R.id.subListView); 
        myAdapter = new MyAdapter(context, foods, images); 
        listView.setAdapter(myAdapter); 
        selectDefult(); 

 

//Popupwindow显示位置控制

//Popupwindow菜单的隐藏方法

// showAsDropDown,默认位置在锚点的左下,如果左下没有空间,就显示在左上 
    public void showAsDropUp(View parent) { 
        popupWindow 
                .showAtLocation(parent, Gravity.LEFT | Gravity.BOTTOM, 0, 90); 
        popupWindow.showAsDropDown(parent, 0, 0);

        // 显示的位置

        // 使其聚集 
        popupWindow.setFocusable(true); 
        // 使其允许在外点击消失 
        popupWindow.setOutsideTouchable(true); 
        // 刷新状态 
        popupWindow.update(); 
    }

    // 隐藏菜单 
    public void dismiss() { 
        popupWindow.dismiss(); 
    }

布局文件:Popupwindow中横向并排两个ListView;

              adapter中的ListView-item左边图片,右边textview。

*****************************************

自定义的MyListView,开启子线程,动态更新UI。

class MyListView extends ListView implements Runnable == 继承ListView,实现Runnable方法。

//主要override 的方法:

@Override 
    public boolean onTouchEvent(MotionEvent event) { 
        switch (event.getAction()) { 
        case MotionEvent.ACTION_DOWN: 
            if (mLastDownY == 0f && mDistance == 0) { 
                mLastDownY = event.getY(); 
                return true; 
            } 
            break;

        case MotionEvent.ACTION_CANCEL: 
            break;

        case MotionEvent.ACTION_UP: 
            if (mDistance != 0) { 
                mStep = 1; 
                mPositive = (mDistance >= 0); 
                /** 
                 * post 
                 * 
                 * Causes the Runnable to be added to the message queue. The 
                 * runnable will be run on the user interface thread. 
                 * 触发子线程被添加到消息队列事件。该子线程将运行在用户接口线程。 This method can be invoked 
                 * from outside of the UI thread only when this View is attached 
                 * to a window. 只有当View控件被加入一个窗体,该方法从外部UI线程被调用 
                 */ 
                this.post(this); 
                return true; 
            } 
            mLastDownY = 0f; 
            mDistance = 0; 
            break;

        case MotionEvent.ACTION_MOVE: 
            if (mLastDownY != 0f) { 
                mDistance = (int) (mLastDownY - event.getY()); 
                if ((mDistance < 0 && getFirstVisiblePosition() == 0 && getChildAt( 
                        0).getTop() == 0) 
                        || (mDistance > 0 && getLastVisiblePosition() == getCount() - 1)) { 
                    mDistance /= 2; 
                    scrollTo(0, mDistance); 
                    return true; 
                } 
            } 
            mDistance = 0; 
            break; 
        } 
        return super.onTouchEvent(event); 
    }

 

注:现在还是熟练代码的阶段,好多东西都不清楚啊,需要学习的太多了。

Android安卓二级菜单

阅读数 2186

Android 二级菜单

阅读数 5088

没有更多推荐了,返回首页