2014-09-25 67 views
1

我有3個字:大象,房子和拍手。 我有2個按鈕:上一個和下一個。 我有一個TextView來顯示單詞。 TextView應該在開始時顯示大象,然後如果我點擊下一個,它應該顯示房子,如果我再次點擊下一個,它應該顯示拍手。 如果我點擊之前它應該再次顯示房子。如何在每次點擊Android中的按鈕時顯示一個新單詞?

我該如何編碼? 我想過創建一個字符串數組: String words [] = {「elephant」,「house」,「clap」};

預先感謝您。

回答

1

你可以試試下面的代碼。這假定你有一個關於Android活動如何結合在一起的基本知識,並且你已經習慣於創建按鈕和文字視圖。

// Class fields: 

private String[] strings = new String[]{"elephant", "house", "clap", "etc."}; 
private TextView display; 



// In your onCreate(): 

display = (TextView) findViewById(R.id.display); 
Button nextButton = findViewById(R.id.next_button); 
Button prevButton = findViewById(R.id.prev_button); 

nextButton.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
     moveString(1); 
    } 
}); 

prevButton.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
     moveString(-1); 
    } 
}); 



// In the class: 

public void moveString(int move) { 
    int newString = currentString + move; 
    if (newString >= strings.length) { 
     // if the new position is past the end of the array, go back to the beginning 
     newString = 0; 
    } 
    if (newString < 0) { 
     // if the new position is before the beginning, loop to the end 
     newString = strings.length - 1; 
    } 
    currentString = newString; 
    display.setText(strings[currentString]); 
} 
+0

它很好用,馬克!驚人的速度你能夠編碼!比方說,我想讓它循環並從頭開始,這很容易嗎? – user3814312 2014-09-26 18:29:35

+0

非常容易做到 - 我已經寫了'return;''你可以用'currentString = 0'替換它''總是回到開頭,或者你可以使用兩個if語句在每個方向上正確循環 – 2014-09-26 18:40:20

+0

@ user3814312這是否解決了你的問題? – 2014-09-27 15:14:02

相關問題