【问题标题】:Android - Correct placement of listeners with ExpandableListAdapterAndroid - 使用 ExpandableListAdapter 正确放置侦听器
【发布时间】:2016-07-31 15:41:25
【问题描述】:

我有一个名为 ExpandableListAdapter 的类,它扩展了 BaseExpandableListAdapter。我的 getChildView 方法如下所示:

    @Override
   public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
        ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this.context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_item, null);
    }

    tv_questionAmountResult = (TextView) convertView.findViewById(R.id.tv_questionAmountResult);
    tv_correctAmountResult = (TextView) convertView.findViewById(R.id.tv_correctAmountResult);
    tv_wrongAmountResult = (TextView) convertView.findViewById(R.id.tv_wrongAmountResult);

    bt_allQuestions = (Button) convertView.findViewById(R.id.bt_allQuestions);
    bt_correctQuestions = (Button) convertView.findViewById(R.id.bt_correctQuestions);
    bt_wrongQuestions = (Button) convertView.findViewById(R.id.bt_wrongQuestions);

    return convertView;
}

我的其他类 ActTraining 在 onCreate 方法中使用 ExpandableListAdapter:

 ExpandableListAdapter listAdapter;
 ExpandableListView expListView;

    // get the listview
    expListView = (ExpandableListView) findViewById(R.id.topicExpandableListView);

    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);

现在我想为 3 个按钮添加 OnClickListener,但我不确定放置正确。 我是否必须在我的 getChildView 或我的 ActTraining 类中添加监听器?

【问题讨论】:

    标签: android android-layout listview android-adapter


    【解决方案1】:

    对于所有 3 个按钮,您必须将 OnClickListener 放在您的 ExpandableListAdapter.getChildView 中,因为您在每个 childItem 中都有它们的按钮。

    句柄OnClickListener的一些有用链接:

    RecyclerView click listener

    Set a click listener to a RecyclerView

    【讨论】:

    • 问题是我的 ExpandableListAdapter 没有扩展 Activity。所以我不能使用例如 startActivity()。
    • 您可以创建一个callback 方法并将其放入接口中并在您的onClickListener 中调用它,然后在您的活动中实现回调。我编辑了答案并添加了一些有用的链接。
    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    相关资源
    最近更新 更多