Assign a value to each row in the ArrayAdapter

I want to create an ArrayAdapter for a single counter. Thus, each element contains one line (which will be displayed in the counter / list) and one value (for example, identifier). How can I easily save the second value next to each row without introducing a new adapter class?

Regards xZise

+3
source share
2 answers

You can create a class with two fields: one for text and another for ID. And we implement the method toStringas the return value of the text field. Here is an example:

package org.me.adaptertest;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {
    public static class Element {
        private String mText;
        private long mId;

        public Element(String text, long id) {
            mText = text;
            mId = id;
        }

        public long getId() {
            return mId;
        }

        public void setId(long id) {
            mId = id;
        }

        public String getmText() {
            return mText;
        }

        public void setmText(String mText) {
            this.mText = mText;
        }

        @Override
        public String toString() {
            return mText;
        }
    }

    private List<Element> mItems;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mItems = new ArrayList<MainActivity.Element>();
        mItems.add(new Element("Element 1", 1));
        mItems.add(new Element("Element 2", 2));
        mItems.add(new Element("Element 3", 3));
        setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
                android.R.id.text1, mItems));
        getListView().setOnItemClickListener(new ListView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,
                        "ID is " + mItems.get(position).getId(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}
+5
source

You can use hashmap to match the identifier of each line.

0

Source: https://habr.com/ru/post/1769583/


All Articles