2015-07-11 43 views
0

如何編輯通過下面顯示的代碼創建的按鈕?例如,我想將按鈕i = 4的文本從「test4」更改爲「changed4」。我該怎麼做?如何編輯由此代碼創建的按鈕?

containerLayout = (LinearLayout) findViewById(R.id.containerLayout); 
    for (int i = 0; i < 6; i++) { 
     Button button = new Button(this); 
     button.setBackgroundResource(R.drawable.button); 
     button.setTextAppearance(this, R.style.ButtonFontStyle); 
     button.setTextColor(getResources().getColor(R.color.white)); 
     button.setTypeface(Typeface.DEFAULT_BOLD); 
     button.setId(i); 
     button.setText("test"+i); 
     containerLayout.addView(button); 
    } 

回答

1

你可以這樣說:

containerLayout = (LinearLayout) findViewById(R.id.containerLayout); 
for (int i = 0; i < 6; i++) { 
    Button button = new Button(this); 
    button.setBackgroundResource(R.drawable.button); 
    button.setTextAppearance(this, R.style.ButtonFontStyle); 
    button.setTextColor(getResources().getColor(R.color.white)); 
    button.setTypeface(Typeface.DEFAULT_BOLD); 
    button.setId(i); 
    if(i == 4){ 
     button.setText("changed"+i); 
    }else{ 
     button.setText("test"+i); 
    } 
    containerLayout.addView(button); 
} 

或者,如果你想將其設置爲「TEST4」,後來改變它,你可以做這樣的事情。

HashMap<Integer, Button> buttons = new HashMap<Integer, Button>(); 
containerLayout = (LinearLayout) findViewById(R.id.containerLayout); 
for (int i = 0; i < 6; i++) { 
    Button button = new Button(this); 
    button.setBackgroundResource(R.drawable.button); 
    button.setTextAppearance(this, R.style.ButtonFontStyle); 
    button.setTextColor(getResources().getColor(R.color.white)); 
    button.setTypeface(Typeface.DEFAULT_BOLD); 
    button.setId(i); 
    button.setText("test"+i); 
    containerLayout.addView(button); 
    buttons.put(i, button) 
} 
.... 
buttons.get(4).setText("changed4"); 
+0

謝謝你,我需要第二個。 –

相關問題