gpt4 book ai didi

java - 无法从适配器调用 Activity 函数

转载 作者:行者123 更新时间:2023-12-01 17:54:18 25 4
gpt4 key购买 nike

我想从适配器调用 Activity 函数。我正在尝试这样的事情:

 ((MainActivity)mCtx).SampleVoid(); 

但我收到错误:java.lang.ClassCastException:android.app.Application 无法转换为

public void SampleVoid(){

Toast.makeText(this,"Testowa metoda",Toast.LENGTH_LONG).show();
}

最佳答案

发生该错误是因为您尝试将应用程序上下文转换为 Activity 上下文。首先,我不建议您在适配器内发送和存储上下文。我建议您创建一个接口(interface),以便在适配器执行特定操作时与 Activity 进行通信。例如:

Activity 代码:

SomeAdapter adapter = new SomeAdapter();
adapter.setOnAdapterActionListener(new OnAdapterActionListener() {
@Override
public void onSomeAdapterAction() {
Toast.makeText(this,"Testowa metoda",Toast.LENGTH_LONG).show();
}
});

适配器代码:

public class SomeAdapter extends ArrayAdapter<String> { // extend from the same adapter that you are extending now.
private OnAdapterActionListener onAdapterActionListener;

public SomeAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) {
super(context, resource, objects);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(onAdapterActionListener != null) {
onAdapterActionListener.onSomeAdapterAction();
}
}
});
return view;
}

public void setOnAdapterActionListener(OnAdapterActionListener onAdapterActionListener) {
this.onAdapterActionListener = onAdapterActionListener;
}
}

interface OnAdapterActionListener {
void onSomeAdapterAction();
}

关于java - 无法从适配器调用 Activity 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60746346/

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