大家好,我在练习中使用的代码遇到了问题。
事实是,它对提供教程的人有用,但对我不起作用。我的问题是如何解决?

 package bt.sismo;


import android.os.Bundle;
import android.view.View;
import android.widget.Toast;//
import android.widget.ListView;//
import android.widget.ListAdapter;//
import android.widget.ArrayAdapter;//
import android.widget.AdapterView;//
import android.app.Activity;//

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] foods = {"Bacon", "Ham", "Tuna", "Candy", "Meatball", "Potato"};
        ListAdapter bryansAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, foods);
        ListView bryansListView = (ListView) findViewById(R.id.bryansListView);
        bryansListView.setAdapter(bryansAdapter);

        bryansListView.setOnClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String food = String.valueOf(parent.getItemAtPosition(position));
                        Toast.makeText(MainActivity.this, food, Toast.LENGTH_LONG).show();
                    }
                }

        );
    }
}


稍后它在logcat中给我这个错误

    Error:(26, 23) error: no suitable method found for setOnClickListener(<anonymous OnItemClickListener>)
    method View.setOnClickListener(OnClickListener) is not applicable
    (argument mismatch; <anonymous OnItemClickListener> cannot be converted to OnClickListener)
    method AdapterView.setOnClickListener(OnClickListener) is not applicable
    (argument mismatch; <anonymous OnItemClickListener> cannot be converted to OnClickListener)

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

最佳答案

您正在调用setOnClickListener并传入OnItemClickListener

更改此:

bryansListView.setOnClickListener(...)

对此:

bryansListView.setOnItemClickListener(...)

关于java - 来自Android应用的错误setOnClickListener,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36917725/

10-10 01:56