Android 台灣中文網
標題:
新手發問程式碼重複的寫法
[打印本頁]
作者:
zzhsu
時間:
2017-8-24 00:49
標題:
新手發問程式碼重複的寫法
本帖最後由 zzhsu 於 2017-8-24 00:51 編輯
小弟剛接觸android app兩個禮拜
在書中看到一個程式碼的寫法
<pre style="">public class MainActivity extends AppCompatActivity {
TextView txvR,txvB,txvG;
View colorBlock;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txvR = (TextView) findViewById(R.id.RedCode);
txvB = (TextView) findViewById(R.id.BlueCode);
txvG = (TextView) findViewById(R.id.GreenCode);
colorBlock = findViewById(R.id.ColorBlockTextView);
btn = (Button) findViewById(R.id.button);
}
public void onChangeColor(View v){
Random x = new Random();
int red = x.nextInt(256);
txvR.setText(""+red);
txvR.setTextColor(Color.rgb(red,0,0));
int blue = x.nextInt(256);
txvB.setText(""+blue);
txvB.setTextColor(Color.rgb(0,0,blue));
int green = x.nextInt(256);
txvG.setText(""+green);
txvG.setTextColor(Color.rgb(0,green,0));
colorBlock.setBackgroundColor(Color.rgb(red,green,blue));
btn.setBackgroundColor(Color.rgb(red,green,blue));
}
}</pre>
複製代碼
以下程式碼一直重複
int green = x.nextInt(256);
txvG.setText(""+green);
txvG.setTextColor(Color.rgb(0,green,0));
複製代碼
在java中,可以把以上代碼自訂一個method後,重覆使用
但在android中,不知如何實現自訂一個method後,重覆使用
在此請教各位前輩,不吝指教,感激不盡...
作者:
b770428
時間:
2017-8-25 15:12
本帖最後由 b770428 於 2017-8-25 15:33 編輯
其實方式是一樣的
在AppCompatActivity一個method
呼叫的時候在OnCreate Method或其他自訂的Method裡面呼叫就
public void test(int rgb,String colormessage,TextView v){v.setText(""+colormessage);
v.setTextColor(int rgb);}
呼叫得時候再把參數帶入用Color.rgb()這個Method所回傳的參數帶入就行了
歡迎光臨 Android 台灣中文網 (https://apk.tw/)
Powered by Discuz! X3.1