Search code examples
androidtextviewgettextsettext

I have 200 textviews and i want to know which one was pressed then how to change the text


I have a problem... have been thinking about it for a while now and been looking on line and still haven't come up with a clear explanation...

I have a number of textviews and have set onClickListeners to each of them.. and when the user clicks on one of them I want them to have the ability to change the text to another set of string array options which I have created progammatically. When the user selects an option the text should change to the option they choose. (I.e. TextView was A now it is B. hope this makes sense.. anyway... )

The current solution was to set a OnClickListener to every TextView and when someone pressed it an individual dialog showed. But I found that if I do this the code would be so long it would take an eternity to code so am hoping someone has a more elegant way of coding such a long process =(

So I guess my question would be... 1) is there a way I can find out which text view was pressed and then change the text of that TextView being pressed within a single method? to save me having to code 1000 alert dialogs...

https://i.sstatic.net/LRJGz.png


Solution

  • I would suggest holding the textviews in an array, like so:

    TextView[] textViewArray = new TextView[textViewCount];
    

    Then using a for loop assign each one a tag of integer - it's position

    textViewArray.setTag(i)
    

    And add an onClickListener to each one, again using a for loop:

    textviewArray[i].setOnClickListener(etc...)
    

    Then when one is clicked, you can use get the position of view that was clicked. This will require a custom method inside of your:

    textviewArray.setOnClickListener(new customOnClickListener())
    

    Where your customOnClickListner is like this:

        private class customOnClickListener implements CompoundButton.{
        public void OnClick(View view){
            int position = (Integer) view.getTag()
            ///Do more code here - your processing
        }
    }
    

    Hope that makes sense :) For your for loops, you could use for(i = 0, i