目標:利用SeekBar來控制背景RGB的顏色
在 activity_main.xml中:
1,新增三個SeekBar
2,SeekBar的最大值要設為255
3,設定Layout及SeekBar的id
在MainActivity.java中:
1,宣告元件layout、SeekBar,並將元件指向為剛剛在XML中設定的元件
2,宣告OnSeekBarChangeListener,並將這個監聽器命名
3,在監聽器中的onProgressChanged方法內設定LinearLayout的BackgroundColor,其中R、G、B的數值是分別從seekbar-sbR、sbG、sbB中取得值
4,將sbR、sbG、sbB這三個監聽器都指向為剛剛建立的監聽器
在 activity_main.xml中:
1,新增三個SeekBar
2,SeekBar的最大值要設為255
3,設定Layout及SeekBar的id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
android:orientation="vertical" | |
android:padding="16dp" | |
android:id="@+id/lin"> | |
<SeekBar | |
android:id="@+id/sbR" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:layout_marginBottom="8dp" | |
android:max="255"/> | |
<SeekBar | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:id="@+id/sbG" | |
android:layout_marginTop="8dp" | |
android:layout_marginBottom="8dp" | |
android:max="255"/> | |
<SeekBar | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:id="@+id/sbB" | |
android:layout_marginTop="8dp" | |
android:max="255"/> | |
</LinearLayout> |
在MainActivity.java中:
1,宣告元件layout、SeekBar,並將元件指向為剛剛在XML中設定的元件
2,宣告OnSeekBarChangeListener,並將這個監聽器命名
3,在監聽器中的onProgressChanged方法內設定LinearLayout的BackgroundColor,其中R、G、B的數值是分別從seekbar-sbR、sbG、sbB中取得值
4,將sbR、sbG、sbB這三個監聽器都指向為剛剛建立的監聽器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
lin = (LinearLayout) findViewById(R.id.lin); | |
sbR = (SeekBar) findViewById(R.id.sbR); | |
sbG = (SeekBar) findViewById(R.id.sbG); | |
sbB = (SeekBar) findViewById(R.id.sbB); | |
//宣告監聽器,名稱為SBL | |
SeekBar.OnSeekBarChangeListener SBL = new SeekBar.OnSeekBarChangeListener() { | |
@Override | |
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { | |
//設定LinearLayout的背景色 | |
lin.setBackgroundColor(Color.rgb(sbR.getProgress(),sbG.getProgress(),sbB.getProgress())); | |
} | |
@Override | |
public void onStartTrackingTouch(SeekBar seekBar) { | |
} | |
@Override | |
public void onStopTrackingTouch(SeekBar seekBar) { | |
} | |
}; | |
//將三個SeekBar的監聽器都指定為SBL | |
sbR.setOnSeekBarChangeListener(SBL); | |
sbG.setOnSeekBarChangeListener(SBL); | |
sbB.setOnSeekBarChangeListener(SBL); | |
} |
留言
張貼留言