【问题标题】:How to add OnClickListener to image button in the ListView Header in Android?如何在 Android 的 ListView Header 中将 OnClickListener 添加到图像按钮?
【发布时间】:2012-10-26 10:06:44
【问题描述】:

我在 android 的 ListView 中添加了一个自定义标题。 Header 的布局 xml 文件包含一个 Image 按钮。如何向此 ImageButton 添加 OnClickListener

标题布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#336699">

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/add" />



</LinearLayout>

绑定 ListView 的代码(我已经创建了一个自定义的 Adapter)

 ListView listView1 = (ListView) findViewById(R.id.listView1);
    LocationAdapter adapter = new LocationAdapter(this,R.layout.listrow,webresult);
    View header = (View)getLayoutInflater().inflate(R.layout.listheader, null);
    listView1.addHeaderView(header);
    listView1.setAdapter(adapter);

【问题讨论】:

  • 抱歉,我已经编辑了问题。
  • header.findViewById(R.id.imageButton1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* ... */ }});
  • @TomaszGawel 谢谢。您的解决方案有效!
  • 但不推荐。 ListViews 不应该有 onClickListeners 而是 onItemClickListeners。只是说;)

标签: android android-listview onclicklistener


【解决方案1】:

当您向列表视图添加标题时,它被视为列表的元素0。因此,您无需添加onClickListener,而是像处理列表中的常规行一样添加:

    listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          if(position==0) //do your stuff
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多