从活动传递数据到RecyclerAdapter – Android

huangapple go评论105阅读模式
英文:

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:

  1. public String getName(){
  2. return f_name;
  3. }

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:

  1. public String getName(){
  2. return f_name;
  3. }

Now how do I call this in my adapter class? I'm not able to access my getName() method here !

答案1

得分: 0

当然。您应该使用一个参数来创建适配器。例如:

  1. class MyAdapter(val string: String) : RecyclerView.Adapter()

然后在活动中创建适配器:

  1. recyclerView.adapter = MyAdapter(myString)

就这样。您没有指定语言,所以我使用了 Kotlin。

英文:

Sure. You should create the adapter with a parameter. For example:

  1. class MyAdapter(val string: String) : RecyclerView.Adapter()

and then you create the adapter in the activity:

  1. recyclerView.adapter = MyAdapter(myString)

And that's it. You didn't specify a language so I used kotlin.

答案2

得分: 0

Agustine的答案是针对kotlin的,这里是Java版本的代码:

  1. public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
  2. private String myString;
  3. private Context context;
  4. MyAdapter(Context context, String myString) {
  5. this.context = context;
  6. this.myString = myString;
  7. }
  8. }

然后在你的活动中:

  1. MyAdapter adapter = new MyAdapter(this, "要传递给适配器的字符串");

就是这样。你可以在这里了解更多关于RecyclerView和RecyclerAdapter的信息。

英文:

Agustine's answer is for kotlin, here's the java version

  1. public class MyAdapter extends RecyclerView.Adapter&lt;MyAdapter.ViewHolder&gt;() {
  2. private String myString;
  3. private Context context;
  4. MyAdapter(Context context, String myString) {
  5. this.context = context;
  6. this.myString = myString;
  7. }
  8. }

and then in your activity

  1. MyAdapter adapter = new MyAdapter(this, &quot;string you want to pass to adapter&quot;)

That's it. You can learn more about recyclerview and recyclerAdapter here

huangapple
  • 本文由 发表于 2020年7月22日 21:11:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63035027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定