Android ExpandableListView简単使用(一)の仿QQ追加パケット机能

32371 ワード

Xzhiのブログからの転載を明記してください(http://blog.csdn.net/CSDN_zhi/article/details/61200010)、他人の勤勉な労働成果を尊重してください.ありがとうございます.
前言
あと数日でユビキタスの試合が始まるので、お忙しいところから少し時間を割いてまとめて、準備試合でExpandableListViewの使用に遭遇しました.以前にもExpandableListViewに遭遇したことがありますが、SimpleExpandableListAdapterアダプタを使用するだけで簡単に実現できます.SimpleExpandableListAdapterは使いやすいが、複雑な機能には向いておらず、データソースの取得も不便である.例えば、私は一昨日の試合準備訓練でこのようなトラブルに遭遇しました.Android側はPC側からデータを取得してExpandableListViewの形式で展示しています.この時のデータソースは死んでいません.SimpleExpandableListAdapterも実現できますが、本人はかなり面倒だと思います.これには、BaseExpandableListAdapterアダプタが必要です.
効果図
私は簡単にBaseExpandableListAdapterを使ってQQを模倣してグループを追加する機能を実現します.まず効果図を見てみましょう.
xmlコード
ダイレクトコード
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"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/add"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:onClick="add"
        android:src="@drawable/add" />

    <ExpandableListView
        android:id="@+id/expandableListView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/add"
         >
    ExpandableListView>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/add"
        android:layout_marginBottom="20dp"
        android:layout_toRightOf="@+id/add"
        android:text="    " />

RelativeLayout>

child_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/cName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_marginBottom="32dp"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/imageView1"
        android:text="TextView" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="80dp"
        android:layout_height="90dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="16dp"
        android:src="@drawable/ic_launcher" />

RelativeLayout>

group_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/gCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/gName"
        android:layout_alignBottom="@+id/gName"
        android:layout_alignParentRight="true"
        android:layout_marginRight="66dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/gName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="10dp"
        android:text="TextView" />

RelativeLayout>

JAvaコード
MainActivity.java
public class MainActivity extends Activity
{
    MyAdapter adapter;
    ExpandableListView ep;
    /*       */
    List groupList;
    /*       */
    List> childList;

    ListcList;

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

        ep = (ExpandableListView)findViewById(R.id.expandableListView1);

        init();
        epClick();
    }

    public void init()
    {
        groupList = new ArrayList();
        groupList.add(new GroupInfo("    "));

        cList = new ArrayList();
        cList.add(new ChildInfo("  ", BitmapFactory.decodeResource(getResources(), R.drawable.pic6)));
        cList.add(new ChildInfo("  ", BitmapFactory.decodeResource(getResources(), R.drawable.pic5)));
        cList.add(new ChildInfo("  ", BitmapFactory.decodeResource(getResources(), R.drawable.pic3)));
        cList.add(new ChildInfo("  ", BitmapFactory.decodeResource(getResources(), R.drawable.pic4)));
        cList.add(new ChildInfo("  ", BitmapFactory.decodeResource(getResources(), R.drawable.pic1)));
        cList.add(new ChildInfo("  ", BitmapFactory.decodeResource(getResources(), R.drawable.pic2)));

        childList = new ArrayList>();
        childList.add(cList);
        adapter = new MyAdapter(groupList, childList, this);
        ep.setAdapter(adapter);
    }

    /**
     * ep    
     * 
     * @time 2017-3-10   10:55:41
     */
    public void epClick()
    {
        ep.setOnItemLongClickListener(new OnItemLongClickListener()
        {
            public boolean onItemLongClick(AdapterView> parent, View view, int position, long id)
            {
                final EditText editText = new EditText(MainActivity.this);
                editText.setHint("     ");
                new AlertDialog.Builder(MainActivity.this)
                .setTitle("    ")
                .setView(editText)
                .setNegativeButton("  ", new OnClickListener()
                {

                    public void onClick(DialogInterface dialog, int which)
                    {
                        try
                        {
                            /**              */
                            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);
                            // true    
                            field.set(dialog, true);
                            dialog.dismiss();
                        }
                        catch (Exception e)
                        {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        // TODO Auto-generated method stub

                    }
                })
                .setPositiveButton("  ", new OnClickListener()
                {

                    public void onClick(DialogInterface dialog, int which)
                    {

                        Field field = null;
                        try
                        {
                            field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);
                            String string = editText.getText().toString();
                            if (!(string.equals("")))
                            {
                                field.set(dialog, true);
                                dialog.dismiss();
//                              cList.clear();
                                cList = new ArrayList();
                                cList.add(new ChildInfo(string, BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)));
//                              childList = new ArrayList>();
                                childList.add(cList);
                                adapter.notifyDataSetChanged();
                            }
                            else
                            {
                                Toast.makeText(MainActivity.this, "      ", 0).show();
                                field.set(dialog, false);
                                dialog.dismiss();
                            }
                        }
                        catch (Exception e)
                        {
                            // TODO: handle exception
                        }
                    }
                }).show();
                return false;
            }
        });
    }
    public void add(View v)
    {
        final EditText editText = new EditText(this);
        editText.setHint("      ");
        new AlertDialog.Builder(this)
        .setTitle("    ")
        .setView(editText)
        .setNegativeButton("  ", new OnClickListener()
        {

            public void onClick(DialogInterface dialog, int which)
            {
                try
                {
                    Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);
                    //  true,       
                    field.set(dialog, true);
                    dialog.dismiss();
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                }
            }
        })
        .setPositiveButton("  ", new OnClickListener()
        {

            public void onClick(DialogInterface dialog, int which)
            {
                Field field = null;
                try
                {
                    /**              */
                    field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);

                    String string = editText.getText().toString();
                    if (!(string.equals("")))
                    {
                        groupList.add(new GroupInfo(string));
                        adapter.notifyDataSetChanged();
                        //  true,       
                        field.set(dialog, true);
                        dialog.dismiss();
                    }
                    else
                    {
                        //  false,        
                        field.set(dialog, false);
                        dialog.dismiss();
                        Toast.makeText(MainActivity.this, "      ", 0).show();
                    }
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                }
            }

        }).show();
    }
}

MyAdapter.java
public class MyAdapter extends BaseExpandableListAdapter
{
    /*       */
    List groupList;
    /*       */
    List> childList;
    Context context;

    public MyAdapter(List groupList, List> childList, Context context)
    {
        super();
        this.groupList = groupList;
        this.childList = childList;
        this.context = context;
    }

    class GroupView
    {
        TextView groupName;
        TextView count;
    }

    class ChildView
    {
        ImageView pic;
        TextView childName;
    }

    /********************* Group ************************/

    public int getGroupCount()
    {
        return groupList.size();
    }

    public Object getGroup(int groupPosition)
    {
        return groupList.get(groupPosition);
    }

    public long getGroupId(int groupPosition)
    {
        return groupPosition;
    }

    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
    {
        GroupView gView = null;
        if (convertView == null)
        {
            gView = new GroupView();
            convertView = LayoutInflater.from(context).inflate(R.layout.group_item, null);
            gView.groupName = (TextView) convertView.findViewById(R.id.gName);
            gView.count = (TextView) convertView.findViewById(R.id.gCount);
            convertView.setTag(gView);
        }
        else
        {
            gView = (GroupView) convertView.getTag();
        }
        GroupInfo groupInfo = groupList.get(groupPosition);
        gView.groupName.setText(groupInfo.getName());
        if(groupPosition==0)
        {

            gView.count.setText(""+childList.get(groupPosition).size());
        }
        else
        {
            gView.count.setText("0");
        }

        return convertView;
    }

    /**************************** Child ***************************/

    int i = 0;
    public int getChildrenCount(int groupPosition)
    {
        if(groupPosition == 0)
        {
            i = childList.get(groupPosition).size();
        }
        else
        {
            Toast.makeText(context, "      ", 0).show();
            i = 0;
        }
        return i;
    }

    public Object getChild(int groupPosition, int childPosition)
    {
        return childList.get(groupPosition).get(childPosition);
    }

    public long getChildId(int groupPosition, int childPosition)
    {
        return childPosition;
    }

    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
    {
        ChildView cView = null;
        if (convertView == null)
        {
            cView = new ChildView();
            convertView = LayoutInflater.from(context).inflate(R.layout.child_item, null);
            cView.childName = (TextView) convertView.findViewById(R.id.cName);
            cView.pic = (ImageView) convertView.findViewById(R.id.imageView1);
            convertView.setTag(cView);
        }
        else
        {
            cView = (ChildView) convertView.getTag();
        }
        ChildInfo childInfo = childList.get(groupPosition).get(childPosition);
        cView.pic.setImageBitmap(childInfo.getChildPic());
        cView.childName.setText(childInfo.getChildName());
        return convertView;
    }

    public boolean hasStableIds()
    {
        return false;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition)
    {
        return false;
    }

}

ChildInfo.java
/**
 * 
 * @function Child   
 * @author Xzhi
 * @time 2017-3-10   10:00:41
 * Copyright (c) 2017 Xzhi All Rights Reserved.
 *
 */
public class ChildInfo
{
    String childName;
    Bitmap childPic;

    public ChildInfo(String childName, Bitmap childPic)
    {
        super();
        this.childName = childName;
        this.childPic = childPic;
    }

    public String getChildName()
    {
        return childName;
    }

    public void setChildName(String childName)
    {
        this.childName = childName;
    }

    public Bitmap getChildPic()
    {
        return childPic;
    }

    public void setChildPic(Bitmap childPic)
    {
        this.childPic = childPic;
    }

}

GroupInfo.java
/**
 * 
 * @function Group   
 * @author Xzhi
 * @time 2017-3-10   9:55:41 
 * Copyright (c) 2017 Xzhi All Rights Reserved.
 *
 */
public class GroupInfo
{
    String name;
    int count;

    public GroupInfo(String name)
    {
        super();
        this.name = name;
        this.count = count;
    }

    public String getName()
    {
        return name;
    }

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

    public int getCount()
    {
        return count;
    }

    public void setCount(int count)
    {
        this.count = count;
    }

}

上のコードは簡単で説明する必要はありません.時間が迫っているので、「友達追加」という機能はまだ実現していないので、試合が終わってから実現するつもりです.もしプロジェクトがあなたに役に立つなら、githubで私のプロジェクトを開始することを歓迎します.もちろん、メッセージやforkを歓迎するアドバイスがあれば、歓迎します.ソースをクリックしてダウンロード
支持を賞賛する.
もし私の文章があなたに役に立つと思ったら、勝手に賞をあげてください.あなたの支持は私に創作を続けることを奨励します!
Android ExpandableListView简单使用(一)之仿QQ添加分组功能_第1张图片
Android ExpandableListView简单使用(一)之仿QQ添加分组功能_第2张图片