Android ExpandableListVIew使用BaseExpandableListAdapter

时间:2011-05-05 11:43:10

标签: android

我正在使用扩展的MyExpandableListAdapter BaseExpandableListAdapter和我在我的适配器中实现了BaseExpandableListAdapter的所有方法,我创建了扩展ExpandableListActivity的MyExpadableListActivity。 MyExpandableListAdapter是MyExpadableListActivity的内部类。 我使用xml视图添加子项和分组UI(过去在下面)。 当我运行应用程序时它的显示很好。 我的问题是,我在MyExpadableListActivity中覆盖了ExpandableListActivity的onChildClick(....)方法。当我运行我的代码时,它不能用于onChildClick方法。 我如何使用这种情况或其他建议实现onChildClick(...)方法.. 希望有人指出我做错了什么...... 如果有人指出我如何能够实现解决方案,请感激不尽。 。

public class MyExpadableListActivity extends ExpandableListActivity implements
    ExpandableListView.OnChildClickListener {
    ExpandableListAdapter mAdapter;
    Context mContext;   
    static final String groups[] = { "Chats", "Contacts (289)",
        "Group Chat (7)", "e-Card  (137)", "Pending  (37)",
        "Bookmarks" };

static final String children[][] = {
        { "ListofChats" },
        { "Group", "groupt01", "groupt02", "groupt03" },
        { "Groupd 01", "", "Group  02", "", "Group  03", "" },
        { "E-Card-01", "", "E-Card-02", "",
                "Business Card Received", "" },
        { " Req", "", " Req", "", " Req", "" } };

private static final String TAG = "Hookup";
XMPPConnection connection = SignInMainActivity.connection;

@Override
public void onCreate(Bundle savedInstanceState) {       
        super.onCreate(savedInstanceState);                 
    mAdapter = new MyExpandableListAdapter(this);
    setListAdapter(mAdapter);
    registerForContextMenu(getExpandableListView());        
}
@Override
public boolean onChildClick(ExpandableListView parent, View v,
        int groupPosition, int childPosition, long id) {
    // TODO Auto-generated method stub
    System.out.println("Insidded onContextItemSelected");
    return super.onChildClick(parent, v, groupPosition, childPosition, id);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    menu.setHeaderTitle("Hookup Menu");
    menu.add(0, 0, 0, R.string.hello);
}

public boolean onContextItemSelected(MenuItem item) {
    System.out.println("Insidded onContextItemSelected");

    Log.i(TAG, "onContextItemSelected");
    ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item
            .getMenuInfo();

    String title = ((TextView) info.targetView).getText().toString();
    int type = ExpandableListView
            .getPackedPositionType(info.packedPosition);

    if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
        int groupPos = ExpandableListView
                .getPackedPositionGroup(info.packedPosition);
        int childPos = ExpandableListView
                .getPackedPositionChild(info.packedPosition);
        Toast.makeText(this,title + ": Child " + childPos + " clicked in                    group " + groupPos, Toast.LENGTH_SHORT).show();
        return true;
    } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
        int groupPos = ExpandableListView
                .getPackedPositionGroup(info.packedPosition);
        Toast.makeText(this, title + ": Group " + groupPos + " clicked",
                Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}

public class MyExpandableListAdapter extends BaseExpandableListAdapter {
    Context mContext;

    public MyExpandableListAdapter() {
        // TODO Auto-generated constructor stub
    }

    public MyExpandableListAdapter(Context context) {
        mContext = context;

    }

    public Object getChild(int groupPosition, int childPosition) {
        Log.i(TAG, "getChild");
        return children[groupPosition][childPosition];
    }

    public long getChildId(int groupPosition, int childPosition) {
        Log.i(TAG, "getChildId");
        return childPosition;
    }

    public int getChildrenCount(int groupPosition) {
        Log.i(TAG, "getChildId");
        return children[groupPosition].length;
    }

    public View getChildView(int groupPosition, int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        Log.i(TAG, "getChildView");

        LayoutInflater layoutInflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = null;

        TextView tt = null;
        if (groupPosition == 4) {
            v = layoutInflater.inflate(R.layout.button_group, null);
        } else {
            v = layoutInflater.inflate(R.layout.album_row, null);
            tt = (TextView) v.findViewById(R.id.text1);

            String myText = this.getChild(groupPosition, childPosition)
                    .toString();

            tt.setText(myText);
            CheckBox cb = (CheckBox) v.findViewById(R.id.checkbox);
            cb.setVisibility(View.VISIBLE);

            if (groupPosition == 0) {
                ImageView icon = (ImageView) v.findViewById(R.id.rowicon);
                icon.setImageResource(R.drawable.add_picture);
            } else {
                ImageView icon = (ImageView) v.findViewById(R.id.rowicon);
                icon.setImageResource(R.drawable.add_picture);

            }
        }

                    return v;
    }

    public Object getGroup(int groupPosition) {
        Log.i(TAG, "getGroup");
        return groups[groupPosition];
    }

    public int getGroupCount() {
        Log.i(TAG, "getGroupCount");
        return groups.length;
    }

    public long getGroupId(int groupPosition) {
        Log.i(TAG, "getGroupId");
        return groupPosition;
    }

    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        TextView groupTitle = null;
        ImageView imgDot;
        LayoutInflater layoutInflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = null;
        v = layoutInflater.inflate(R.layout.button_group, null);
        groupTitle = (TextView) v.findViewById(R.id.TextView01);
        String myText = this.getGroup(groupPosition).toString();
        groupTitle.setText(myText);
        imgDot = (ImageView) v.findViewById(R.id.ImageView01);
        imgDot.setVisibility(View.VISIBLE);
        return v;
    }
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        Log.i(TAG, "isChildSelectable");
        return true;
    }
    public boolean hasStableIds() {
        Log.i(TAG, "hasStableIds");
        return true;
    }
    public void registerDataSetObserver(DataSetObserver observer) {
    }
} // closing of MyExpandableListAdapter 
} // closing of MyExpadableListActivity

我的xml视图如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
android:layout_width="fill_parent" android:layout_height="wrap_content" 
android:minHeight="?android:attr/listPreferredItemHeight" 
android:gravity="center_vertical" 
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft" 
android:paddingRight="?android:attr/scrollbarSize"
android:layout_weight="1" android:background="#fafafa">
<ImageView android:id="@+id/rowicon" android:layout_width="wrap_content"  
android:layout_height="fill_parent" android:layout_marginRight="6dip" /> <TextView   
android:id="@+id/text1"
android:layout_width="wrap_content" android:layout_height="wrap_content" 
android:layout_weight="1"
/>
<CheckBox android:id="@+id/checkbox" android:layout_width="wrap_content" 
android:layout_height="wrap_content" android:layout_marginRight="2dip" 
android:focusable="true" android:clickable="true" android:gravity="center_vertical" 
android:orientation="vertical" android:duplicateParentState="true" 
android:visibility="visible"
android:text="myTest"
/> </LinearLayout> 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
android:layout_width="fill_parent" android:layout_height="wrap_content"   
android:minHeight="?android:attr/listPreferredItemHeight"   
android:gravity="center_vertical" 
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft" 
android:paddingRight="?android:attr/scrollbarSize"
android:layout_weight="1" android:background="#fafafa">

    

3 个答案:

答案 0 :(得分:4)

BaseExpandableListAdapter是一个功能:public boolean isChildSelectable(int groupPosition, int childPosition)。此函数返回Default false。将其更改为:return true。你的onChildClickListener将被调用!

答案 1 :(得分:2)

你忘了注册setOnChildClickListener(...),但它不能用 onChildClick( )方法。

编辑1:您只需要在onCreate方法中添加一行:

@Override
public void onCreate(Bundle savedInstanceState) {       
    super.onCreate(savedInstanceState);                 
    mAdapter = new MyExpandableListAdapter(this);
    setListAdapter(mAdapter);
    getExpandableListView().setOnChildClickListener(this); //This should fix issue.
    registerForContextMenu(getExpandableListView());   //ContextMenu event override onChildClick and onGroupClick. Remove this line    
}

编辑2:尝试this链接。如果它对你没有帮助,我建议你不要使用BaseExpandableListAdapter。使用SimpleExpandableListAdapter,重写4个方法:getChildView(),getGroupView(),getChildrenCount()和getGroupCount()。一切都应该是好的。

不要忘记写评论。如果这没有帮助,我会尝试找到更多的想法。

答案 2 :(得分:0)

我尝试在Kotlin中使用BaseExpandableListAdapter 实现 Android ExpandableListView。

我没有发布布局的XML代码。

Kotlin的主要活动:

import android.app.Activity
import android.os.Bundle
import android.widget.ExpandableListAdapter
import android.widget.ExpandableListView
import java.util.ArrayList

class expandable_sticky_kotlin: Activity() {
     var listAdapter: ExpandableListAdapter? = null
     var exp_view: ExpandableListView? = null
     var list: MutableList<String>? = null
     val childList:HashMap<String,List<String>>?=null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_expandable_sticky_header)
        reloadData()
        exp_view = findViewById(R.id.lvExp)
        listAdapter = ExpandableAda(this,list,childList)
        exp_view!!.setAdapter(listAdapter)

    }

    fun reloadData()
    {
        list!!.add("top250")
        list!!.add("nowShowing")
        list!!.add("comingSoon")

        // Adding child data
        val top250 = ArrayList<String>()
        top250.add("The Shawshank Redemption")
        top250.add("The Godfather")
        top250.add("The Godfather: Part II")
        top250.add("Pulp Fiction")
        top250.add("The Good, the Bad and the Ugly")
        top250.add("The Dark Knight")
        top250.add("12 Angry Men")
        top250.add("Dark knight")
        top250.add("POTC")

        val nowShowing = ArrayList<String>()
        nowShowing.add("The Conjuring")
        nowShowing.add("Despicable Me 2")
        nowShowing.add("Turbo")
        nowShowing.add("Grown Ups 2")
        nowShowing.add("Red 2")
        nowShowing.add("The Wolverine")
        nowShowing.add("Deadpool2")
        nowShowing.add("Raazi")


        val comingSoon = ArrayList<String>()
        comingSoon.add("2 Guns")
        comingSoon.add("The Smurfs 2")
        comingSoon.add("The Spectacular Now")
        comingSoon.add("The Canyons")
        comingSoon.add("Europa Report")
        comingSoon.add("Avengers4")
        comingSoon.add("Meri apni movie")

        childList!!.put(list!!.get(0), top250) // Header, Child data
        childList!!.put(list!!.get(1), nowShowing)
        childList!!.put(list!!.get(2), comingSoon)

    }
}

ExpandableView的适配器:

import android.content.Context
import android.database.DataSetObserver
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import android.widget.ExpandableListAdapter
import android.widget.TextView
import java.util.concurrent.ConcurrentLinkedQueue

class ExpandableAda(val context:Context,val list:List<String>?,val Child:HashMap<String,List<String>>?) : BaseExpandableListAdapter()
{


    var mContext = context
       var mparent_list = list
    var mChild = Child


    override fun onGroupCollapsed(p0: Int) {
        println("collpased")
    }
    override fun isEmpty(): Boolean {
        return false
    }

    override fun registerDataSetObserver(p0: DataSetObserver?)
    {
        println("here")
        val observers = ConcurrentLinkedQueue<DataSetObserver>()
        println("here")
        if (p0!=null) {
            observers.add(p0)
            println("here")
        }
    }

    override fun getChild(p0: Int, p1: Int): Any {
        return mChild!!.get(mparent_list!!.get(p0))!!.get(p1)
    }

    override fun onGroupExpanded(p0: Int) {
       print("Expanded")
    }

    override fun getCombinedChildId(p0: Long, p1: Long): Long
    {
        return p0
    }

    override fun getGroupId(p0: Int): Long {

        return p0.toLong()
    }

    override fun isChildSelectable(p0: Int, p1: Int): Boolean {
        return true
    }

    override fun hasStableIds(): Boolean {
        return true
    }

    override fun getChildView(p0: Int, p1: Int, p2: Boolean, p3: View?, p4: ViewGroup?): View {
        var title:String = getChild(p0,p1) as String
        var myTest:View = p4!!


            var infalInflater = this.mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            myTest = infalInflater.inflate(R.layout.list_item, null)
        var lblListItem:TextView = myTest!!.findViewById(R.id.lblListItem)
        lblListItem.text = title
        return myTest
    }

    override fun areAllItemsEnabled(): Boolean {
        return true
    }

    override fun getChildId(p0: Int, p1: Int): Long {
        return p1.toLong()//To change body of created functions use File | Settings | File Templates.
    }

    override fun getCombinedGroupId(p0: Long): Long {
        return p0
    }

    override fun getGroupView(p0: Int, p1: Boolean, p2: View?, p3: ViewGroup?): View {
    var title:String = mparent_list!!.get(p0)
        var myTest:View = p3!!

            var inflater = this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        myTest = inflater.inflate(R.layout.list_group, null)
          var lblListHeader:TextView = myTest!!.findViewById(R.id.lblListHeader)

        lblListHeader.text = title
        return myTest!!
    }

    override fun unregisterDataSetObserver(p0: DataSetObserver?) {
        val observers = ConcurrentLinkedQueue<DataSetObserver>()
        if (p0!=null)
        {
            observers.remove(p0)
        }
    }

    override fun getGroupCount(): Int {

        return mparent_list!!.size
    }

    override fun getGroup(p0: Int): Any {
        return mparent_list!!.get(p0)
    }

    override fun getChildrenCount(p0: Int): Int {
        return mChild!!.get(mparent_list!!.get(p0))!!.size
    }

}