gpt4 book ai didi

java - Android 应用程序中的 setOnClickListener 错误

转载 作者:行者123 更新时间:2023-12-01 06:50:00 27 4
gpt4 key购买 nike

嘿伙计们,我在练习时使用的代码遇到了问题。问题是它对提供教程的人有用,但对我不起作用。我的问题是如何解决它?

 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com