2013-05-04 20 views
0

我是新來的Java和我們的最終項目的數組,而不是創建3000個活動,我決定使用單個數組來容納我所有的字符串。我現在遇到的問題是,當我按下按鈕更改屏幕上的字符串時,它會跳到最後或者以某種方式將它們一起添加。我希望它一次顯示出一個字符串,並且不能,因爲我一生都在想它。無法在按鈕上顯示數組中的一個字符串按

這裏是我的代碼:

public class MainActivity extends Activity { 

    MediaPlayer Snake; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     final String[] Lines = {"So begins the story of our hero.","His name is Solid Snake.","He is an international spy, an elite solider, and quite the ladies man.", 
       "Snake likes to sneak around in his cardboard box.","Most enemies aren't smart enough to catch him in it."}; 
     Snake = MediaPlayer.create(this, R.raw.maintheme); 
     Snake.start(); 
     final TextView tv = (TextView)findViewById(R.id.textView1); 
     Button N = (Button)findViewById(R.id.next); 
     Button B = (Button)findViewById(R.id.back); 
     int count = 0; 
     tv.setText(Lines[count]); 

     N.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       String temp = ""; 
       for(int l=1; l<Lines.length; l++){ 
        temp=temp+Lines[l]; 
        tv.setText(""+temp); 
       } 

      } 

      }); 
     }; 

的主要問題是在按下按鈕。我到處搜索,根本找不到任何答案。任何幫助,將不勝感激。

+0

你確實是一個挽救生命的人。非常感謝! – user2350807 2013-05-04 22:16:19

+0

如果您的問題已解決,請不要忘記選擇正確的答案;) – Alexey 2013-05-04 22:25:11

回答

0

單擊按鈕時,文本將通過數組中的每個條目進行更改,並在最後一個條目上完成。由於這種情況很快發生,你只能看到最後一個值。

您的onClick()方法應更改爲只調用setText()一次,並增加活動中保存的計數器。

public class MainActivity extends Activity { 
    private int currentLine = 0; 
    ... 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     ... 
     tv.setText(Lines[currentLine]); 

     N.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (currentLine + 1 < Lines.length) { 
        currentLine++; 
        tv.setText(Lines[currentLine]); 
       } 
      } 
     }); 
     ... 
    } 
    ... 
} 
相關問題