5

I have a class called StringsA and inside it there is an array of strings:

public class StringsA {

static String Names[] = {"Larry", "Moe", "Curly", "John"};  

}

In my main class there is a Button and a TextView. What I want is to set the text of the TextView to a different word from the strings array each time the Button is clicked. For example; the current item is "Moe", when the button is clicked, the TextView changes to "John" (the change is random, not by order).

My current Activity code:

    setContentView(R.layout.main);
    Button a = (Button) findViewById(R.id.button1);
    TextView b = (TextView) findViewById(R.id.tv);        

    Resources i = getResources();
    i.getResourceName(StringsA.Names);

    a.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {               

        }
    });
}

I'm getting error in i.getResourceTypeName. How should I change the TextView text to one of the strings when the Button is clicked?

2 Answers 2

25

Take full advantage of Android resources, load your values from a string array defined in strings.xml. E.g.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
</resources>

Then:

  private static final Random RAND = new Random();

  public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    Button myButton = (Button) findViewById(R.id.button1);
    TextView myTextField = (TextView) findViewById(R.id.tv);     

    final String[] values = getResources().getStringArray(R.array.planets_array);
    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {     
          String nextValue = values[RAND.nextInt(values.length)]          
          myTextField.setText(nextValue);
        }
    });
  }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Marvin, u helped me =)
You're welcome. If your question is solved, you can mark the answer as accepted using the checkmark next to it.
Perfecto Perfecto Perfecto
0

add the below two lines in onClick method

int readomIndex = (int)(Math.random() * 3);
b.setText( Names[readomIndex]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.