綁定帳號登入

Android 台灣中文網

打印 上一主題 下一主題

[求助] 新手發問程式碼重複的寫法

[複製連結] 查看: 2419|回覆: 1|好評: 0
跳轉到指定樓層
樓主
zzhsu | 收聽TA | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
發表於 2017-8-24 00:49

馬上加入Android 台灣中文網,立即免費下載應用遊戲。

您需要 登錄 才可以下載或查看,沒有帳號?註冊

x
本帖最後由 zzhsu 於 2017-8-24 00:51 編輯

小弟剛接觸android app兩個禮拜
在書中看到一個程式碼的寫法
  1. <pre style="">public class MainActivity extends AppCompatActivity {

  2.     TextView txvR,txvB,txvG;
  3.     View colorBlock;
  4.     Button btn;
  5.     @Override
  6.     protected void onCreate(Bundle savedInstanceState) {
  7.         super.onCreate(savedInstanceState);
  8.         setContentView(R.layout.activity_main);

  9.         txvR = (TextView) findViewById(R.id.RedCode);
  10.         txvB = (TextView) findViewById(R.id.BlueCode);
  11.         txvG = (TextView) findViewById(R.id.GreenCode);

  12.         colorBlock = findViewById(R.id.ColorBlockTextView);
  13.         btn = (Button) findViewById(R.id.button);

  14.     }


  15.     public void onChangeColor(View v){

  16.         Random x = new Random();
  17.         


  18.         int red = x.nextInt(256);
  19.         txvR.setText(""+red);
  20.         txvR.setTextColor(Color.rgb(red,0,0));

  21.         int blue = x.nextInt(256);
  22.         txvB.setText(""+blue);
  23.         txvB.setTextColor(Color.rgb(0,0,blue));

  24.         int green = x.nextInt(256);
  25.         txvG.setText(""+green);
  26.         txvG.setTextColor(Color.rgb(0,green,0));

  27.         colorBlock.setBackgroundColor(Color.rgb(red,green,blue));
  28.         btn.setBackgroundColor(Color.rgb(red,green,blue));

  29.     }
  30. }</pre>
複製代碼



以下程式碼一直重複
  1.   int green = x.nextInt(256);
  2.   txvG.setText(""+green);
  3.   txvG.setTextColor(Color.rgb(0,green,0));
複製代碼


在java中,可以把以上代碼自訂一個method後,重覆使用
但在android中,不知如何實現自訂一個method後,重覆使用
在此請教各位前輩,不吝指教,感激不盡...





「用Android 就來APK.TW」,快來加入粉絲吧!
Android 台灣中文網(APK.TW)
收藏收藏 分享分享 分享專題
用Android 就來Android 台灣中文網(https://apk.tw)
回覆

使用道具 舉報

沙發
b770428 | 收聽TA | 只看該作者
發表於 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 就來Android 台灣中文網(https://apk.tw)
回覆 支持 反對

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則