Wednesday, April 20, 2011

Auto change backgroundcolor by Seek bar in Android




main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/myScreen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<SeekBar
android:id="@+id/mySeekingBar_R"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
<SeekBar
android:id="@+id/mySeekingBar_G"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
<SeekBar
android:id="@+id/mySeekingBar_B"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="255"
    android:progress="0"/>
</LinearLayout>
 
SeekColorActivity.java 
 package com.exercise.seekcolor;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.SeekBar;

public class SeekColorActivity extends Activity {

private int seekR, seekG, seekB;
SeekBar redSeekBar, greenSeekBar, blueSeekBar;
LinearLayout mScreen;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mScreen = (LinearLayout) findViewById(R.id.myScreen);
    redSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_R);
    greenSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_G);
    blueSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_B);
    updateBackground();

    redSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
    greenSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
    blueSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);

}

private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener()
{

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
  boolean fromUser) {
// TODO Auto-generated method stub
 updateBackground();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};

private void updateBackground()
{
 seekR = redSeekBar.getProgress();
 seekG = greenSeekBar.getProgress();
 seekB = blueSeekBar.getProgress();
 mScreen.setBackgroundColor(
  0xff000000
  + seekR * 0x10000
  + seekG * 0x100
  + seekB
  );
}
} 

No comments:

Post a Comment