简体   繁体   English

将值从MainActivity传递到自定义listview适配器类

[英]Passing value from MainActivity to custom listview adapter class

I want to pass a String value to my custom listview adapter class. 我想将String值传递给自定义listview适配器类。 I did it as according to the code below but it's not working. 我按照下面的代码进行了操作,但无法正常工作。

MainActivity.java MainActivity.java

private ArrayList<Item> generateData(String book_name)
{    
    MyAdapter adapter=new MyAdapter(getApplicationContext(),null);
    adapter.message = "hello"; 

MyAdapter.java MyAdapter.java

public class MyAdapter extends ArrayAdapter<Item> {

    public String message;

and then in the getView 然后在getView中

@Override
    public View getView(int position, View convertView, ViewGroup parent) 
    {            
        title.setText(itemsArrayList.get(position).getTitle());
        if(message == "hello")
        {
            //do something here
        }

Thanks for the help 谢谢您的帮助

What I think is happening is that your creating the adapter which calls getView before the message is set. 我认为正在发生的事情是您创建了在设置消息之前调用getView的适配器。 So in your custom adapter you change the constructor so it takes the message. 因此,在您的自定义适配器中,您可以更改构造函数,以便接收消息。

public MyAdapter(Context context, Int resource, ArrayList<value> values, String message) {
    //your current code
    this.message = message 
}

The problem is that your string comparision is wrong. 问题是您的字符串比较错误。 You should use equals method instead of == . 您应该使用equals方法而不是== So the comparision line should looks like this: 因此,比较线应如下所示:

if ("hello".equals(message)) {
    //your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM