二级菜单android_android 二级菜单 - CSDN
  • Android安卓二级菜单

    2018-05-03 16:34:57
    一、首先在AndroidStudio里创建个moudle(如果不想新创建项目,且自己的电脑配置扛得住的情况下)、在activity_main.xml里布局ExpandableListView<?xml version="1.0" encoding="utf-8"...

    一、首先在AndroidStudio里创建个moudle(如果不想新创建项目,且自己的电脑配置扛得住的情况下)

    二、在activity_main.xml里布局ExpandableListView

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <ExpandableListView android:id="@+id/expandableListView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></ExpandableListView>
    
    </RelativeLayout>
    三、创建父级目录item_group.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="vertical"
        android:background="#8BCF28"
        >
    <TextView   android:id="@+id/tv_group"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:gravity="center"
        android:text="父目录"
        />
    
    
    

    </LinearLayout>

    四、创建子级目录item_child.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"
        >
        <ImageView  android:id="@+id/child_img"
            android:src="@mipmap/ic_launcher"
            android:layout_width="30dp"
            android:layout_height="30dp" />
        <TextView   android:id="@+id/tv_child"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="子目录"/>
    五、创建MyExpandableListView的优化类
    package com.example.expandablelistview;
    
    import android.content.Context;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseExpandableListAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class MyExpandableListView extends BaseExpandableListAdapter {
        Context context;
        private String [] groups;
        private String [][] childs;
    
        public MyExpandableListView(Context context, String[] groups, String[][] childs) {
            this.context = context;
            this.groups = groups;
            this.childs = childs;
        }
    
        @Override
        public int getGroupCount() {
            return groups.length;
        }
    
        @Override
        public int getChildrenCount(int groupPosition) {
            return childs[groupPosition].length;
        }
    
        @Override
        public Object getGroup(int groupPosition) {
            return groups[groupPosition];
        }
    
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return childs[groupPosition][childPosition];
        }
    
        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }
    
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }
    
        @Override
        public boolean hasStableIds() {
            return true;
        }
    
    
    //填充父级目录
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            GroupHolder groupholder =null;
            if (convertView==null){
                groupholder =new GroupHolder();
                convertView=View.inflate(context,R.layout.item_group,null);
                groupholder.tv_group=convertView.findViewById(R.id.tv_group);
                convertView.setTag(groupholder);
            }else{
                groupholder= (GroupHolder) convertView.getTag();
            }
            groupholder.tv_group.setText(groups[groupPosition]);
            return convertView;
            }
    
       
    //填充子级目录
     @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ChildHolder childholder=null;
            if (convertView==null){
                childholder=new ChildHolder();
                convertView=View.inflate(context,R.layout.item_child,null);
                childholder.child_img=convertView.findViewById(R.id.child_img);
                childholder.tv_child=convertView.findViewById(R.id.tv_child);
                convertView.setTag(childholder);
            }else {
                childholder= (ChildHolder) convertView.getTag();
            };
                //childholder.child_img.setImageBitmap(
                childholder.tv_child.setText(childs[groupPosition][childPosition]);
    
            return convertView;
        
    
        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    
      class GroupHolder{
            TextView tv_group;
      }
    
        class ChildHolder{
            ImageView child_img;
            TextView tv_child;
        }
    
    }
    
    五、Mainactivity修改
    package com.example.expandablelistview;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ExpandableListView;
    
    public class MainActivity extends AppCompatActivity {
    
        private ExpandableListView expandableListView;
        private String [] groups={"A","B","C"};
        private String [][] childs={{"A1","A2","A3"},{"B1","B2","B3"},{"C1","C2","C3"}};
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            expandableListView=findViewById(R.id.expandableListView);
            expandableListView.setAdapter(new MyExpandableListView(MainActivity.this,groups,childs));
    
    
        }
    }
    




    展开全文
  • 这种横向的二级菜单在很多的app都有所应用.效果看起来还是非常的美观的.也算是项目需要,自己也就学了一下这个效果,首先说一下逻辑.实现的方式其实并不是很难..只不过逻辑上可能有点复杂.原理其实就是一个按钮.当触发...
    
    

    学习内容:

    1.Android二级横向菜单的实现过程.效果如上图...

     

      这种横向的二级菜单在很多的app都有所应用.效果看起来还是非常的美观的.也算是项目需要,自己也就学了一下这个效果,首先说一下逻辑.实现的方式其实并不是很难..只不过逻辑上可能有点复杂.原理其实就是一个按钮.当触发按钮的时候弹出PopWindow.PopWindow由两个ListView构成..对两个ListView适当的适配.就可以实现这个效果了..

      实现这种效果可以有两种不同的方式..一种是直接在布局文件layout.xml中写..最上方的可以是一个按钮.也可以是多个按钮..多个按钮就可以使用RadioGroup去实现..下方则采用ScrollView去实现也是可以的..

      不过我还是说一下第二种方式..直接用Java去写这个布局..通过使用自定义控件的方式实现这个效果..既然是自定义,那么首先我们需要继承一个布局.布局可以使用LinearLayout或者RelativeLayout.

      setValue()方法..

      setValue()方法是自定义的方法..主要是用于加载布局.以及在布局当中添加相关的View.没有加载任何的xml文件..

    复制代码
       /**
         *  @param textArray: ListView中item对应的text值的集合..
         *  @param viewArray: 当前Layout中需要加入的View.. 
         * */
        @SuppressLint("ResourceAsColor") 
        public void setValue(ArrayList<String> textArray, ArrayList<View> viewArray) {
            if (mContext == null) {
                return;
            }
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
            mTextList = textArray;
            for (int i = 0; i < viewArray.size(); i++) {
                
                //这里就添加了一个View..
                final RelativeLayout r = new RelativeLayout(mContext);
                int maxHeight = (int) (displayHeight * 0.5);   //定义布局的高度..
                
                
                RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, maxHeight);
                r.addView(viewArray.get(i), rl);  //在布局中添加View并指定参数
                
                
                mViewList.add(r);
                r.setTag(SMALL);
                
                //定义最上方的按钮,并在布局中添加这个按钮。并设置按钮的text
                ToggleButton tButton = (ToggleButton) inflater.inflate(R.layout.toggle_button, this, false);
                addView(tButton);
                mToggleList.add(tButton);
                tButton.setTag(i);
                tButton.setText(mTextList.get(i));
                
                //用于实现当PopWindow显示时.再次点击收回PopWindow
                r.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onPressBack();
                    }
                });
    
                r.setBackgroundColor(mContext.getResources().getColor(R.color.popup_main_background));
                
                //当按钮被点击后需要触发的监听
                tButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        
                        
                        ToggleButton tButton = (ToggleButton) view;
                        /** 如果当前点击的按钮与上次的点击不同.则设置当前的按钮处于点击状态 */
                        if (selectedButton != null && selectedButton != tButton) {
                            selectedButton.setChecked(false);
                        }
                        selectedButton = tButton;
                        selectPosition = (Integer) selectedButton.getTag();
                        /** 按钮被点击后,需要触发对应的监听事件.*/
                        startAnimation();
                        if (mOnButtonClickListener != null && tButton.isChecked()) {
                            mOnButtonClickListener.onClick(selectPosition);
                        }
                    }
                });
            }
        }
    复制代码

      那么设置完了布局的样式后..只有一个ToggleButton按钮.点击后没有任何的效果.我们需要去定义一个新的View视图.用于点击按钮后需要显示的弹出窗.那么这个弹出窗也需要自定义..

     弹出窗则采用两个ListView的形式进行显示.在布局中将两个ListView进行添加.对每一个ListView设置相应的适配器.然后将这个View添加到上面的主View当中.就可以实现当button被点击后,弹出窗在下方进行显示的效果..

     ChildView() 弹出窗View的布局实现方式..

     这里定义了这个View,并完成相应的初始化操作.设置对应的适配器也就完成了..

    复制代码
    package com.example.view;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    
    import android.content.Context;
    import android.util.AttributeSet;
    import android.util.SparseArray;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    
    import com.example.adapter.TextAdapter;
    import com.example.expandtabview.R;
    
    public class ChildView extends LinearLayout {
        
        private ListView regionListView;   //主ListView
        private ListView plateListView;    //子ListView
        
        //主ListView每一个Item对应的text
        private String LeftFaString[] = new String[] { "美食", "快餐小吃", "火锅", "海鲜/烧烤",
                "特色菜", "香锅/烤鱼", "地方菜", "东南亚菜", "西餐", "日韩料理" };
        //子ListView每一个Item对应的text..采用了二维数组的实现方式..
        private String LeftCh1String[][] = new String[][] {
                { "全部" },
                { "全部", "中式简餐", "地方小吃", "盖浇饭", "米粉米线", "面馆", "麻辣烫", "黄焖鸡米饭",
                        "鸭脖卤味", "饺子馄饨", "炸鸡炸串", "包子/粥", "零食", "生煎锅贴", "冒菜" },
                { "全部", "其他火锅" }, { "全部", "小龙虾" }, { "全部" }, { "全部", "香锅", "烤鱼" },
                { "全部", "鲁菜", "川菜", "其他" }, { "全部" },
                { "全部", "意面披萨", "西式快餐", "其他西餐" }, { "全部", "韩式简餐", "韩国料理" } };
    
        //添加主ListView中的数据信息
        private ArrayList<String> groups = new ArrayList<String>();
        
        //添加子ListView中的数据信息
        private LinkedList<String> childrenItem = new LinkedList<String>();
        
        //稀疏数组
        private SparseArray<LinkedList<String>> children = new SparseArray<LinkedList<String>>();
        //为ListView设置适配器
        private TextAdapter plateListViewAdapter;
        private TextAdapter earaListViewAdapter;
        //监听事件的设置
        private OnSelectListener mOnSelectListener;
        
        private int tEaraPosition = 0;     //用于保存当前主ListView被点击的Item对应的Position.
        private int tBlockPosition = 0;       //用于保存当前子ListView被点击的Item对应的Position.
        
        private String showString = "";
    
        public ChildView(Context context) {
            super(context);
            init(context);
        }
    
        public ChildView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context);
        }
    
    
        private void init(Context context) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            
            //加载布局,绑定ID.
            inflater.inflate(R.layout.view_region, this, true);
            regionListView = (ListView) findViewById(R.id.listView);
            plateListView = (ListView) findViewById(R.id.listView2);
    
            //初始化ListView中每一个item对应的text
            for(int i=0;i<10;i++){
                groups.add(LeftFaString[i]);
                LinkedList<String> tItem = new LinkedList<String>();
                for(int j=0;j<LeftCh1String[i].length;j++){
                    
                    tItem.add(LeftCh1String[i][j]);
                    
                }
                children.put(i, tItem);
            }
    
            //主ListView列表项的适配器
            earaListViewAdapter = new TextAdapter(context, groups,
                    R.drawable.choose,
                    R.drawable.choose_eara_item_selector);
            earaListViewAdapter.setTextSize(12);
            earaListViewAdapter.setSelectedPositionNoNotify(tEaraPosition);
            
            regionListView.setAdapter(earaListViewAdapter);
            
            earaListViewAdapter
                    .setOnItemClickListener(new TextAdapter.OnItemClickListener() {
    
                        @Override
                        public void onItemClick(View view, int position) {
                            if (position < children.size()) {
                                childrenItem.clear();
                                //获取这一页的所有数据信息..然后唤醒适配器更新数据
                                childrenItem.addAll(children.get(position));
                                plateListViewAdapter.notifyDataSetChanged();
                            }
                        }
                    });
            
            if (tEaraPosition < children.size())
                childrenItem.addAll(children.get(tEaraPosition));
            
            
            //子ListView的适配器
            plateListViewAdapter = new TextAdapter(context, childrenItem,
                    R.drawable.choose_item_right,
                    R.drawable.choose_plate_item_selector);
            plateListViewAdapter.setTextSize(12);
            plateListViewAdapter.setSelectedPositionNoNotify(tBlockPosition);
            plateListView.setAdapter(plateListViewAdapter);
            //设置当Item被点击后触发的监听.
            plateListViewAdapter
                    .setOnItemClickListener(new TextAdapter.OnItemClickListener() {
    
                        @Override
                        public void onItemClick(View view, final int position) {
                            //获取被点击的Item的文字数据
                            showString = childrenItem.get(position);
                            if (mOnSelectListener != null) {
                                
                                mOnSelectListener.getValue(showString);
                            }
    
                        }
                    });
            
            if (tBlockPosition < childrenItem.size())
                showString = childrenItem.get(tBlockPosition);
            setDefaultSelect();
    
        }
        
        //设置当前Item的Position.
        public void setDefaultSelect() {
            //默认选择的Item项
            regionListView.setSelection(tEaraPosition);
            plateListView.setSelection(tBlockPosition);
        }
    
        public String getShowText() {
            return showString;
        }
    
        public void setOnSelectListener(OnSelectListener onSelectListener) {
            mOnSelectListener = onSelectListener;
        }
    
        public interface OnSelectListener {
            public void getValue(String showText);
        }
    
    }
    复制代码

      那么最后就剩下适配器了..

      ArrayAdapter<String>

      这里使用了ArrayAdapter适配器.继承与BaseAdapter.可以用于显示文本数据..我们也都知道,适配器必须要实现的方法就是getView()方法了..那么我们就简单的看一下这个方法..

    复制代码
        @SuppressLint("ResourceAsColor") @SuppressWarnings("deprecation")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView view;
            if (convertView == null) {
                view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.choose_item, parent, false);
            } else {
                view = (TextView) convertView;
            }
            view.setTag(position);
            String mString = "";
            if (mListData != null) {
                if (position < mListData.size()) {
                    mString = mListData.get(position);
                }
            } else if (mArrayData != null) {
                if (position < mArrayData.length) {
                    mString = mArrayData[position];
                }
            }
            if (mString.contains("不限"))
                view.setText("不限");
            else
                view.setText(mString);
            view.setTextSize(TypedValue.COMPLEX_UNIT_SP,textSize);
    
            if (selectedText != null && selectedText.equals(mString)) {
                view.setBackgroundDrawable(selectedDrawble);//设置选中的背景图片
            } else {
                view.setBackgroundDrawable(mContext.getResources().getDrawable(normalDrawbleId));//设置未选中状态背景图片
            }
            view.setPadding(20, 0, 0, 0);
            view.setOnClickListener(onClickListener);
            return view;
        }
    复制代码

      适配的工作还是非常的简单的.仅仅一个TextView就可以搞定了.当然我们也可以写一个比较复杂的样式.在一个Layout内部定义一些复杂的控件.就能够实现更好的效果.

      最后再MainActivity中的布局文件中加载这个控件,简单的做一些初始化操作就可以实现了..

    复制代码
    package com.example.expandtabview;
    
    
    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Toast;
    
    import com.example.view.ExpandTabView;
    import com.example.view.ChildView;
    
    public class MainActivity extends Activity {
    
        private ExpandTabView expandTabView;
        private ArrayList<View> mViewArray = new ArrayList<View>();
        private ChildView viewLeft;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
            initVaule();
            initListener();
            
        }
    
        private void initView() {
            
            //初始化控件
            expandTabView = (ExpandTabView) findViewById(R.id.expandtab_view);
            viewLeft = new ChildView(this);
            
        }
    
        private void initVaule() {
            
            mViewArray.add(viewLeft);
            
            //设置顶部数据信息
            ArrayList<String> mTextArray = new ArrayList<String>();
            mTextArray.add("全部");
            expandTabView.setValue(mTextArray, mViewArray);
            expandTabView.setTitle(viewLeft.getShowText(), 0);
            
        }
    
        private void initListener() {
            
            
            viewLeft.setOnSelectListener(new ChildView.OnSelectListener() {
                
                @Override
                public void getValue(String showText) {
                    
                    onRefresh(viewLeft,showText);
                    
                }
            });
            
            
        }
        
        //视图被点击后刷新数据
        private void onRefresh(View view, String showText) {
            
            expandTabView.onPressBack();
            int position = getPositon(view);
            if (position >= 0 && !expandTabView.getTitle(position).equals(showText)) {
                expandTabView.setTitle(showText, position);
            }
            Toast.makeText(MainActivity.this, showText, Toast.LENGTH_SHORT).show();
    
        }
        
        //获取当前的view
        private int getPositon(View tView) {
            for (int i = 0; i < mViewArray.size(); i++) {
                if (mViewArray.get(i) == tView) {
                    return i;
                }
            }
            return -1;
        }
    }
    复制代码

     这里只是贴了一些核心代码.其他的涉及的一些不重要的代码就不在这里粘贴了..最后放一张图片流程.方便大家去理解.最后给出源代码.



    推荐文章

    1、Android面试经验大解密

    2、Android的viewHolder模式解剖

    3、Android中必须学习的七大开源项目(开发项目必看)

    4、如何自学Android, 教大家玩爆Android(成为大神必看)

    5、2016 Google hosts 持续更新【更新 于:2016-08-27】(免费翻墙必备)

    6、Android面试经验总结(面试成功必备)

    7、Android Studio 个性化设置(装逼必备)

    8、Android Studio 2.2 正式起航(玩爆Android Studio 2.2必备)

    Android Studio 2.2 新功能实例代码:

    Android Studio 2.2新功能实例源码(玩爆Android Studio 2.2必备)

    Android Studio 2.2新功能介绍:

    What's new in Android development tools - Google I/O 2016(YouTube视频需要自备梯子)

    【GitHub】https://github.com/xiaole0310

    【csdn博客】http://blog.csdn.net/xiaole0313

    【新浪微博】http://weibo.com/u/5439466748

    【知乎】http://www.zhihu.com/people/yang-shou-le

    【简书】http://www.jianshu.com/users/1a47e8afa34a

    【技术群】279126311 [满]

    【技术群】484572225 [未]

    【Email】ysle0313@gmail.com

    Android Studio 2.2 新功能实例代码:

    Android Studio 2.2新功能实例源码(玩爆Android Studio 2.2必备)

    如果你有好的文章想和大家分享,欢迎投稿,直接向我投递文章链接即可。

    欢迎扫描关注我们的微信公众号(ysle_0313),不要错过每一篇干货~


    一键关注我们微信公众号 ysle_0313

    展开全文
  • 大众点评有一个功能,

    大众点评有一个功能,如图:


    点击左边右边出来对应的内容,其实这个想到了方法很简单,

    首先布局就是二个listview就可以搞定,无非是里面的数据是怎么填充的,

    比如:第一个listview中定义一个List<String>集合比如:这个集合中添加了江西省,浙江省,福建省

    那么江西省下面就有很多市,比如:九江市,南昌市,景德镇市,上饶市等等,那么如果在集合中再存放一个集合,这个集合就存放与省相关的市,

    定义;private List<List<String>> Data2;


    代码如下:

    public class MainActivity extends Activity {
    private ListView lv1,lv2;

    private List<String> Data1;
    private List<List<String>> Data2;

    private Context ctx;
    private MyAdapter myAdapter;
    private MyDataAdapter myDataAdapter ;
    public  int position;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ctx = this;
    lv1 = (ListView) findViewById(R.id.lv1);
    lv2 = (ListView) findViewById(R.id.lv2);


    initData();
    myAdapter = new MyAdapter(); 
    lv1.setAdapter(myAdapter);

    myDataAdapter = new MyDataAdapter();
    lv2.setAdapter(myDataAdapter);

    lv1.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    long arg3) {
    MainActivity.this.position = arg2;
    myDataAdapter.setPosition(position);
    myDataAdapter.notifyDataSetChanged();
    }
    });
    }

    private void initData() {
    Data1 = new ArrayList<String>();
    Data1.add("江西省");
    Data1.add("浙江省");
    Data1.add("福建省");


    List<String> list= new ArrayList<String>();
    list.add("南昌");
    list.add("九江");
    list.add("上饶");
    list.add("赣州");
    list.add("景德镇");
    list.add("抚州");

    List<String> list1= new ArrayList<String>();
    list1.add("温州市");
    list1.add("嘉兴市");
    list1.add("湖州市");
    list1.add("绍兴市");
    list1.add("金华市");
    list1.add("衢州市");

    List<String> list2= new ArrayList<String>();
    list2.add("莆田市");
    list2.add("泉州市");
    list2.add("厦门市");
    list2.add("漳州市");
    list2.add("龙岩市");
    list2.add("三明市");
    Data2 = new ArrayList<List<String>>();

    Data2.add(list);
    Data2.add(list1);
    Data2.add(list2);
    }


    class MyAdapter extends BaseAdapter{

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


    @Override
    public Object getItem(int arg0) {
    return Data1.get(arg0);
    }


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


    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
    TextView tv = new TextView(ctx);
    tv.setText(Data1.get(arg0));
    return tv;
    }
    }


    /*************************************************/
    class MyDataAdapter extends BaseAdapter{
    public int position;
     
    public void setPosition(int position) {
    this.position = position;
    }


    @Override
    public int getCount() {
    return Data2.get(position).size();
    }


    @Override
    public Object getItem(int arg0) {
    return null;
    }


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


    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
    TextView tv = new TextView(ctx);
    List<String> list = Data2.get(position);
    tv.setText(list.get(arg0));
    return tv;
    }
    }
    }


    效果图:



    展开全文
  • android 二级菜单、双ListView 仿美团、购物App二级菜单

    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>
    展开全文
  • 好了,今天是分享一个android实现三级菜单联动效果,这个demo我也折腾了两三个晚上,到了第三级菜单有点复杂,下面带着大家看下代码。项目结构: 为了让大家更有的耐心的阅读, 我先从简单的开始说起,我们先看下...
  • Android开发之中,经常会遇到二级的串联选择菜单,今天自己写了个Demo,实现了一下这种效果。
  • android下拉二级菜单

    2018-10-29 17:25:54
    @TOC) !image
  • 一个实现android二级菜单,三级菜单,多级菜单的实例,主要使用expandablelistview控件,很不错的效果,分享了
  • android 二级菜单、双ListView 仿美团、购物二级菜单
  • Android开发二级下拉菜单Android开发中,我们经常会有碰到下拉列表的需求,比如,城市下拉菜单,美团网界面上价格,食品的类型等等,都用到了这种二级下拉菜单。因此我参考了这个博文 ...先不说其他的,先看看效果图:...
  • 以后填写
  • (1)布局文件没有做更改 (2)在res--menu目录下的main.xml文件中代码如下: android:id="@+id/file" android:title="@string/file"> android:id=
  • 如果要实现二级菜单的话就在标签中嵌套一个menu标签即可: 2、在.java中复写onCreateOptionsMenu方法 该方法的作用是用来加载菜单条目的!所以不能忘记!!! 获取到刚刚的.xml文件 此时运行的话就可以...
  • Android 二级菜单

    2018-11-04 21:52:46
    https://www.cnblogs.com/blog4wei/p/8875889.html
  • Android中实现二级菜单

    2014-03-10 18:27:40
    1.当点击一级分类,修改二级菜单里面的内容。 2.同时一级菜单里的背景变为右边有白色三角的背景。 3.当点击二级菜单的条目时候,Popupwindow消失,并且界面更新对应条目的商品数据。 我的实现思路是:左下...
  • 数据加载篇之二级菜单 数据加载篇之获取及修改默认设置属性值 搜索栏篇 数据加载之二级菜单 二级菜单是动态加载和静态xml布局文件相结合的方式。 以“系统”这一项为例进行分析: 首先是清单文件...
  • android studio直接生成的侧滑导航代码 <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> android:id="@+id/nav_camera" android:...
  • 项目Github托管地址:https://github.com/zhouzhuo810/ZzSecondaryLinkage效果图How to use it ?准备工作①第一步,添加布局 android:id="@+id/zz_linkage" android:
  • **想问一下Android8.1原生的Settings的二级菜单选项如何去掉呢? 比如Network&Intent页面里面的:Airplane mode 、Mobile plan 、 Mobile network** ![图片说明]...
  • 实现方式基本都是自定义view继承自LinearLayout等布局控件,于是自己在Button的基础上添加了popupWindow并进行了简单封装,使用RecyclerView展示数据,实现了带二级菜单的筛选功能。效果图:实现方式:(1)继承自...
1 2 3 4 5 ... 20
收藏数 19,201
精华内容 7,680
关键字:

二级菜单android