英文:
Pass data from activity to recyclerAdapter - Android
问题
I want to pass the data from the Activity containing a recyclerview to its recyclerAdapter class. I just want to use a String in the adapter but I don't know how to get it from the activity. Is there any way to do this? Please keep in mind I want data from Activity to Adapter and not vice versa.
Edit: So in my activity, I have defined a public method:
public String getName(){
return f_name;
}
Now how do I call this in my adapter class? I'm not able to access my getName() method here!
英文:
I want to pass the data from the Activity containing a recyclerview to it's recyclerAdapter class. I just want to use a String in the adapter but I don't know how to get it from the activity. Is there any way to do this? Please keep in mind I want data from Activity to Adapter and not vice a versa
Edit: So in my activity, I have defined a public method:
public String getName(){
return f_name;
}
Now how do I call this in my adapter class? I'm not able to access my getName() method here !
答案1
得分: 0
当然。您应该使用一个参数来创建适配器。例如:
class MyAdapter(val string: String) : RecyclerView.Adapter()
然后在活动中创建适配器:
recyclerView.adapter = MyAdapter(myString)
就这样。您没有指定语言,所以我使用了 Kotlin。
英文:
Sure. You should create the adapter with a parameter. For example:
class MyAdapter(val string: String) : RecyclerView.Adapter()
and then you create the adapter in the activity:
recyclerView.adapter = MyAdapter(myString)
And that's it. You didn't specify a language so I used kotlin.
答案2
得分: 0
Agustine的答案是针对kotlin的,这里是Java版本的代码:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String myString;
private Context context;
MyAdapter(Context context, String myString) {
this.context = context;
this.myString = myString;
}
}
然后在你的活动中:
MyAdapter adapter = new MyAdapter(this, "要传递给适配器的字符串");
就是这样。你可以在这里了解更多关于RecyclerView和RecyclerAdapter的信息。
英文:
Agustine's answer is for kotlin, here's the java version
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>() {
private String myString;
private Context context;
MyAdapter(Context context, String myString) {
this.context = context;
this.myString = myString;
}
}
and then in your activity
MyAdapter adapter = new MyAdapter(this, "string you want to pass to adapter")
That's it. You can learn more about recyclerview and recyclerAdapter here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论