【问题标题】:Android ExpandableListVIew using BaseExpandableListAdapterAndroid ExpandableListVIew 使用 BaseExpandableListAdapter
【发布时间】:2011-08-19 07:39:42
【问题描述】:

我正在使用扩展的 MyExpandableListAdapter BaseExpandableListAdapter 和我在我的适配器中实现 BaseExpandableListAdapter 的所有方法,我创建了扩展 ExpandableListActivity 的 MyExpadableListActivity。 MyExpandableListAdapter 是 MyExpandableListActivity 的内部类。 我正在使用 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">

【问题讨论】:

标签: android


【解决方案1】:

BaseExpandableListAdapter 中有一个函数:public boolean isChildSelectable(int groupPosition, int childPosition)。此函数返回默认 false。将其更改为:返回 true。并且您的 onChildClickListener 将被调用!

【讨论】:

  • 亲爱的理查德我用其他方式解决了我的问题。我创建动态可扩展列表而不使用工作正常的 xml 布局。如果你阅读我的代码,那么你可以看到我也写为 >public boolean isChildSelectable (int groupPosition, int childPosition) { Log.i(TAG, "isChildSelectable");返回真; } ,意味着我已经按照你的建议做了。但现在我的第二种方法工作正常..
  • 嗨 mikedroid 如果你想要我可以提供的解决方案,就像在 stackoverflow 中一样,我无法通过我的完整代码..如果我可以在这里通过我的代码,我会看到任何方法。请ping 我 tonasirinbox(at)gmail(dot)com
【解决方案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()。一切都应该很好。

别忘了写 cmets。如果这没有帮助,我会尝试寻找更多的想法。

【讨论】:

  • 嗨@Pasha 感谢您的快速回复,但我的问题仍然存在。正如您建议的那样,我使用此 ExpandableListView list = this.getExpandableListView(); int childCount = list.getChildCount(); System.out.print("孩子数" + childCount); list.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { System.out.print("Testing"); // TODO 自动生成的方法存根返回 false; } });
  • 我也关注这个站点链接stackoverflow.com/questions/2512436/… 上给出的cmets,但是同样的问题控制仍然没有进入onChildClick 方法。
  • @Pasha 现在我尝试在developer.android.com/resources/samples/ApiDemos/src/com/… 上给出的示例代码并执行此操作 setListAdapter(mAdapter); getExpandableListView().setOnChildClickListener(this); registerForContextMenu(getExpandableListView());并覆盖方法@Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id){ System.out.print("This is the test");返回假; } .但仍然不能控制 onChildClick ...厌倦了我做错了什么..
  • @Pasha 还没有。我也尝试使用 android 开发者网站上给出的代码,正如我在昨天的评论中发布的那样,但仍然不能控制 onChildClick,
  • @Pasha 我发现我在 ExpandableList1.java 上做错的一件事(给出了 android 开发者网站上的示例,你在上一条评论中的链接中提到的内容)是我把 super.onCreate (保存实例状态);在我编码 super.onCreate(savedInstanceState); 时错误的 onCreate 方法的顶部;方法底部的行它工作正常。我对上面给出的问题做同样的事情,但它仍然无法正常工作。
【解决方案3】:

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

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

Kotlin 中的 MAINACTIVITY:

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
    }

}

【讨论】:

    猜你喜欢
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多