繁体   English   中英

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

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

我想将String值传递给自定义listview适配器类。 我按照下面的代码进行了操作,但无法正常工作。

MainActivity.java

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

MyAdapter.java

public class MyAdapter extends ArrayAdapter<Item> {

    public String message;

然后在getView中

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

谢谢您的帮助

我认为正在发生的事情是您创建了在设置消息之前调用getView的适配器。 因此,在您的自定义适配器中,您可以更改构造函数,以便接收消息。

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

问题是您的字符串比较错误。 您应该使用equals方法而不是== 因此,比较线应如下所示:

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

暂无
暂无

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

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