Android ListView 的 setOnClickListener 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3402255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:02:33  来源:igfitidea点击:

setOnClickListener of a ListView not working

androidlistview

提问by dootcher

So I'm trying to set up a setOnClickListenerfor my ListViewbut it's causing a crash in my program for some reason when I try... I'm quite new to programming so when it comes to troubleshooting I can't really do anything sadly :( my code is below so any ideas on what could be wrong would be extremely helpful:

所以我正在尝试setOnClickListener为我的设置一个,ListView但是当我尝试时它由于某种原因导致我的程序崩溃...... (我的代码在下面,所以任何关于可能出错的想法都会非常有帮助:

public class HomePageActivity extends Activity {
    //ListView that holds the items
    ListView lstTest;

    //Array Adapter that holds the ArrayList and displays the items on the ListView
    AlertsAdapter arrayAdapter;

    //List that hosts the items
    ArrayList<Alerts> alrts = null;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homepage);

        //Initialize the ListView
        lstTest = (ListView)findViewById(R.id.lstText);

        //Initialize the ArrayList
        alrts = new ArrayList<Alerts>();

        //Initialize the array adapter
        arrayAdapter = new AlertsAdapter(HomePageActivity.this, R.layout.listitems,alrts);

        //Set the above adapter as the adapter of choice for our list
        lstTest.setAdapter(arrayAdapter);

        lstTest.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(
                HomePageActivity.this,
                PromotionActivity.class
                );
                startActivity(intent);
            }
        });
        //... ... ...
    }
} 

Any thoughts? I'm stuck :(

有什么想法吗?我被卡住了:(

Edit:Posting error log file from ddms:

编辑:从 ddms 发布错误日志文件:

08-04 04:14:26.351: ERROR/AndroidRuntime(8882): FATAL EXCEPTION: main
08-04 04:14:26.351: ERROR/AndroidRuntime(8882): java.lang.RuntimeException: Unable to start activity ComponentInfo{hypenyte.bdutcher.promopost/hypenyte.bdutcher.promopost.HomePageActivity}: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.access00(ActivityThread.java:125)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.os.Looper.loop(Looper.java:123)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at java.lang.reflect.Method.invoke(Method.java:521)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at dalvik.system.NativeStart.main(Native Method)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882): Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.widget.AdapterView.setOnClickListener(AdapterView.java:750)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at hypenyte.bdutcher.promopost.HomePageActivity.onCreate(HomePageActivity.java:58)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     ... 11 more

I saw that it said I probably want setOnItemClickListenerwhich is originally what I had coded it as, but that it wouldn't work since eclipse told me my code was wrong with it.

我看到它说我可能想要setOnItemClickListener它最初是我编码的,但是它不起作用,因为 eclipse 告诉我我的代码有问题。

回答by Mathias Conradt

You need to use setOnItemClickListener()

你需要使用 setOnItemClickListener()

and then new android.widget.AdapterView.OnItemClickListener()

进而 new android.widget.AdapterView.OnItemClickListener()

not new View.OnItemClickListener()

不是 new View.OnItemClickListener()

回答by Jayson Tamayo

Instead of using setOnClickListener, try to use setOnItemClickListener

而不是使用setOnClickListener,尝试使用setOnItemClickListener

回答by Maragues

If using Butterknife, check that you don't have OnClick annotation for an AdapterView descentant (Spinner, ListView, etc.)

如果使用 Butterknife,请检查您是否没有 AdapterView 后代(Spinner、ListView 等)的 OnClick 注释

@OnClick(R.id.spinner_id)

Calling ButterKnife.inject(this, view);will throw the exception

调用ButterKnife.inject(this, view);会抛出异常

Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead

Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead

回答by amit pandya

firstly set the value inside your main activity where your using your listview:

首先在您使用列表视图的主要活动中设置值:

new android.widget.AdapterView.OnItemClickListener()

in place of adapter of your listview:

代替您的列表视图的适配器:

  new AdapterView.OnItemClickListener() 

So finally it looks like:

所以最后它看起来像:

this.listView.setItemsCanFocus(false);
this.listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(android.widget.AdapterView<?> parent, View view, int position, long id) {

 }

when you are using any custom view to populate the data inside listview.

当您使用任何自定义视图填充列表视图中的数据时。

Then in your main Activity file.xml in the parent layout{ inside which listview is there} set this option:

然后在您的主 Activity file.xml 中的父布局{里面有 listview} 设置这个选项:

    android:descendantFocusability="blocksDescendants"

and if you are using any buttons/textview inside listview, set this property on that textview/button:

如果您在列表视图中使用任何按钮/文本视图,请在该文本视图/按钮上设置此属性:

    android:focusable="false"
    android:focusableInTouchMode="false"

For scroll optionin your listview just add this line inside activity:

对于列表视图中的滚动选项,只需在活动中添加这一行:

 listView=(ListView)findViewById(R.id.container);
 listView.setNestedScrollingEnabled(true);

As per i understood i am giving answer, and i hope it will help, if anyone found some corrections or helpful, they are welcome.

据我所知,我正在给出答案,我希望它会有所帮助,如果有人发现一些更正或有帮助的,欢迎他们。

回答by Djek-Grif

In my case I try to add onClickListener for spinner and I've got the same problem. I've crated workaround with touch listener. Sometimes we need it for hideKeyBoard or send some analyticEvent:

在我的情况下,我尝试为微调器添加 onClickListener 并且我遇到了同样的问题。我已经用触摸监听器制作了解决方法。有时我们需要它用于 hideKeyBoard 或发送一些 analyticEvent:

someSpinner.setOnTouchListener { _, event ->  onTouchSomeSpinner(event)}

fun onTouchSomeSpinner(event: MotionEvent): Boolean {
        if(event.action == MotionEvent.ACTION_UP) {
            view.hideKeyBoard()
            view.analyticsEvent()
            ...
        }
        return false
}