[英]method call from adapter class to activity
Adapter: 适配器:
check_list_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JPrequirements.prepareSelection(v, getAdapterPosition());
}
});
JPrequirements
is the activity. JPrequirements
是活动。 and prepareSelection
is non-static method inside activity. 而
prepareSelection
是活动内部的非静态方法。 I cannot access it from adapter. 我无法从适配器访问它。
ERROR: 错误:
non static method cannot be referenced from a static context
非静态方法不能从静态上下文中引用
Which is right. 哪个是对的。 that's why I tried with:
这就是为什么我尝试使用:
JPrequirements().prepareSelection(v, getAdapterPosition()); // Creating an instance...
But, the problem is I lost all activity component here. 但是,问题是我在这里丢失了所有活动组件。 eg.
例如。 layout components and other supporting variables.
布局组件和其他支持变量。 I don't want that.
我不要 What is the best way to deal with this?
处理此问题的最佳方法是什么? How can I get updated value from adapter to activity?
如何从适配器到活动获取更新值? So, I can display it real-time.
因此,我可以实时显示它。
Thanks. 谢谢。
You can achieve this via interface
. 您可以通过
interface
实现此目的。 Firstly, define an interface
class as: 首先,将
interface
类定义为:
public interface ActivityAdapterInterface {
public void prepareSelection(View v, int position);
}
Now, implement the interface
in your Activity
as: 现在,在“
Activity
实现interface
为:
public class JPrequirements extends AppCompatActivity implements ActivityAdapterInterface {
...
public void prepareSelection(View v, int position) {
// cool stuff here
}
...
}
Make sure you pass this
interface reference to your Adapter
via its constructor. 确保通过
Adapter
的构造函数this
接口引用传递给Adapter
。 Then finally call it on click as: 然后,最终通过点击将其称为:
check_list_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mActivityAdapterInterface.prepareSelection(v, getAdapterPosition());
}
});
[EDIT] [编辑]
To provide the interface
to your Adapter
provide it the constructor. 要为您的
Adapter
提供interface
,请为其提供构造函数。
public class YourAdapter ... {
private ActivityAdapterInterface mActivityAdapterInterface;
public YourAdapter(..., ActivityAdapterInterface activityAdapterInterface) {
activityAdapterInterface = mActivityAdapterInterface;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.