view raw
Queendevelopers Queendevelopers - 8 months ago 26
Android Question

Is it possible to make click listener to item by string, not by position?

I have thousands of items stored in string-array and none of them are dublicate, And I have displayed them all in list. Now, I want to show the description if text clicked, I will show them in alert Dialog, Is there any way to store value as text click not by position? I don't like to use position to call them because if later I have to remove anything form the list then I have to remake all. So, I want is if text "vishnu" was clicked then Make something called vishnu as id and call the vishnu description according to text click not by position. Thanks in advance!! Here's something we do for position

public void onBindViewHolder(final NameViewHolder holder, final int position) {

holder.textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(), "" + position, Toast.LENGTH_SHORT).show();


Make a Dictionary<string, string> (choose a fitting class yourself. I am not sure but Hashtable probably works) that holds a Key value pair for each string, the key being the string itself and the value being the description you want to be shown when clicking that string.

Then you can use:

Toast.makeText(view.getContext(), myDictionary.get((string)view.getTag()), Toast.LENGTH_SHORT).show();

to get the corresponding text.

Edit 2: How to use a Dictionary (an example):

//In Class
Dictionary<string, string> myDict;

//In ctor (or anywhere before you need it)
string nameString = "Marlon";
string descriptionString = "Some dude currently on stackoverflow.";
myDict = new Hastable<string, string>(); //Create dictionary
myDict.put(nameString, descriptionString); //Fill dictionary

//When you want to get your string
string output = myDict.get("Marlon"); //Get description
descriptionTextView.text = output;  //Put text at screen

Edit: Here you can find the Dictionary docs.