Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android loading string arrays programmatically

Tags:

string

android

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?

like image 935
John Apple Sim Avatar asked Nov 28 '22 08:11

John Apple Sim


1 Answers

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);
        }
    });
  }
like image 98
Vincent Mimoun-Prat Avatar answered Dec 06 '22 12:12

Vincent Mimoun-Prat