简体   繁体   中英

Get value from Activity to custom array adapter

I am creating chat application. So I wanted to add number of messages a user get from his friend. To show that I created custom Array adapter because my listview consists of friend name and notification textview .

好友列表

So, I have the data in my list_of_registerd_users activity:

来自Firebase的数据

How I can send this data to custom array adapter class to set the view of notification:

Custom Array Adapter class :

public class CustomArrayAdapter extends ArrayAdapter<String> {
    private Context mContext;
    private int mRes;
    private ArrayList<String> data;

    private String numOfMsgs;

    public CustomArrayAdapter(Context context, int resource,
                              ArrayList<String> objects) {

        super(context, resource, objects);

        this.mContext = context;
        this.mRes = resource;
        this.data = objects;
    }

    @Override
    public String getItem(int position) {
        // TODO Auto-generated method stub
        return super.getItem(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        LayoutInflater inflater = LayoutInflater.from(mContext);
        row = inflater.inflate(mRes, parent, false);

        String currentUser = getItem(position);

        TextView friendName = (TextView) row.findViewById(R.id.tvFriendName);

        String Frndname = currentUser;
        friendName.setText(Frndname);


        TextView notificationView = (TextView) row.findViewById(R.id.tvNotif);


//here i wanted to get the data noOfMsgs
        Toast.makeText(mContext, "noOfMsgs:" + numOfMsgs, Toast.LENGTH_LONG).show();
            notificationView.setText(noOfMsgs);
        return row;
    }
}

You just need to initialize the adapter and attach the adapter to the ListView

ArrayList<String> items = new ArrayList<>();
items.add(item1);
items.add(item2);
items.add(item3);

CustomArrayAdapter<String> itemsAdapter = new CustomArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listview.setAdapter(itemsAdapter);

You only need to update the list object which you are passing in CustomArrayAdapter and then notify the list.

adapter.notifyDataSetChanged()

As you are passing the list object to adapter so any changes in list will automatically updated in object 'data'. You have to just update the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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