2013-12-15 22 views
0

我有一個按鈕和幾個字符串。Android:當點擊按鈕 - >隨機字符串

我該如何做到這一點,當我點擊按鈕,一個字符串隨機更改爲另一個字符串? 我不知道我應該在這裏複製的內容部分代碼...

按鈕:

<Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/txt_example1" 
     android:layout_centerHorizontal="true" 
     android:background="@drawable/button_newfact" 
     android:minHeight="38dip" 
     android:minWidth="74dp" 
     android:onClick="OnButtonClickChangeTextOfTextView" /> 

這東西在我與YouTube教程所做的MainActivity.java。但它只會變成一個新的文本,而不是另一個字符串。它不是隨機的。

public void OnButtonClickChangeTextOfTextView(View view) 
    { 
     TextView textView = (TextView)findViewById(R.id.txt_example1); 
     textView.setText(""); 
    } 

我希望你能幫助我。祝大家第三次來臨。 :)

+0

你想要哪個隨機字符串?你有一個隨機字符串列表或什麼?你是什​​麼意思_「但它只改變爲一個新的文本,而不是另一個字符串」_? _text_和_string_在文本視圖的情況下是同義詞.. –

+0

您必須在此限定單詞「random」。你的意思是你想從預先存在的字符串數組中選擇一個隨機字符串嗎? – nhgrif

+0

好的。所以我做了5個不同文字的字符串。我希望當我點擊按鈕時,會出現列表中的一個字符串。 – user3104453

回答

0

您可以定義最小值和最大值。 假設你有5串的最小爲1,而在此答案最多5

展望: How do I generate random integers within a specific range in Java?

你可以學習如何生成,有一個範圍的隨機數。然後做出是否別的檢查被賦予什麼樣的隨機數: 這裏是僞:

onClickButton{ 
random = Math.random etc.. 
button = findMyButton (button1) 
button.setText(firstString) if random == 1 
button.setText(secondString) if random == 2 
} 
2

你有5個字符串strings.xml。他們每個人都有一個id。您應該創建這些ID的數組(例如:string1string2等)如下:

private int[] stringIds = {R.string.string1, R.string.string2, R.string.string3, R.string.string4, R.string.string5}; 

然後使用下面的代碼:

private Random rand = new Random(); 
private int[] stringIds = {R.string.string1, R.string.string2, R.string.string3, R.string.string4, R.string.string5}; 
public void OnButtonClickChangeTextOfTextView(View view) 
{ 
    TextView textView = (TextView)findViewById(R.id.txt_example1); 
    int randomNumber = rand.nextInt(5); 
    textView.setText(getResources().getString(stringIds[randomNumber])); 
} 
1

比方說,你在XML中定義的按鈕像這樣:

<Button 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:onClick="randomNumber" /> 

如果在這種情況下,你必須在一個XML文件中定義的字符串,你會作出這樣的參考 它(在這個例子虐待他們R.string.name1等...)

private int[] ids = {R.string.name1 , R.string.name2 , R.string.name3}; 

public void randomNumber(View view){ 

//Now let's say you want a random number between 1 and 10. 

    int number = new Random().nextInt(3);  

    String randomString = getResource().getString(ids[number]); 

    //Then you set the text, let's say to a textView 

    textView.setText(randomString); 

    } 
+0

這將拋出一個'IndexOutOfBoundsException' –

+0

對不起,現在我修好了。 –