从活动传递数据到RecyclerAdapter – Android

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

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&lt;MyAdapter.ViewHolder&gt;() {
    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, &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:

确定