如何从Android适配器中调用片段中的方法 [英] How to call method in fragment from adapter Android
本文介绍了如何从Android适配器中调用片段中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助,所以我有一个带有 RecycleView
的片段,并且在 RecycleView
里面有一个按钮.
I need help so I have a fragment which has a RecycleView
and inside the RecycleView
there is a button.
单击后的按钮必须打开已经在基本片段中声明的对话框,因此我只能像 openDialog(DIALOG_CHECK);
The button after click must open the dialog which already declared in base fragment so I only call like openDialog(DIALOG_CHECK);
现在如何在适配器上调用该对话框,我已经在片段中创建了一个方法,并从适配器中调用了该方法,并出现错误"Java lang空指针"
Now how can I call that dialog on my adapter I already make a method in fragment and call it from the adapter and make an error "Java lang null pointer"
这是我的代码:
DeliveryFragment delivFrag = new DeliveryFragment();
holder.editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
delivFrag.doEdit();
}
});
还有片段
public void doEdit(){
openDialog(DIALOG_EDIT_ITEM);
}
推荐答案
只是一个简单的示例,可以使您更好地理解.使用界面.
Just a simple example for better understanding. Use an interface.
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.ViewHolder> {
private static OnItemClickListener mOnItemClickLister;
public interface OnItemClickListener {
void onItemClicked(View view, int pos);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickLister = listener;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
Button mBtnTest;
Context mContext;
//We also create a constructor that accepts the entire item row
//and does the view lookups to find each subview.
public ViewHolder(Context context, View itemView) {
//Stores the itemView in a public final member variable that can be used
//to access the context from any ViewHolder Instance
super(itemView);
mContext = context;
mBtnTest = (Button) itemView.findViewById(R.id.message_button);
itemView.setOnClickListener(this);
}
@Override public void onClick(View v) {
int position = v.getLayoutDirection();
mOnItemClickLister.onItemClicked(v, position);
}
}
}
片段部分
class FragmentTest extends Fragment implements OnItemClickListener {
TestAdapter adapter = new TestAdapter(); //you can initialize according to your logic
//set the fragment as a listener to adapter
this.adapter.setOnItemClickListener(onItemClickListener);
public void onItemClicked(View view, int pos) {
//do whatever you want here...
}
}
这篇关于如何从Android适配器中调用片段中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文