Change the state of button to pressed - android

What I am trying to achieve: When the button is pressed for the first time, it should get highlighted/ activated / pressed. On the second click on the button it should get unactivated/ not pressed.
and later I want to check that if the button isPressed, do something.
What I tried:
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()) {
case R.id.day_button:
if (v.isPressed() == true) {
v.setPressed(false);
} else if (v.isPressed() == false) {
v.setPressed(true);
}
return true;
I tried this with day_but.isPressed == true also.

you can try with this way change the background state of button when click set the images as a background
Button testButton = (Button) findViewById(R.id.buttonTestButton);
int status = 0;//GLOBAL VARIABLE : the status of the Button ( 0 or 1 )
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//toggle picture
if (status == 0) {
testButton.setBackgroundResource(R.drawable.alternatepicture);
status=1 ; // change the status to 1 so the at the second clic , the else will be executed
}
else {
testButton.setBackgroundResource(R.drawable.fakpicture);
status =0;//change the status to 0 so the at the second clic , the if will be executed
}
}//end void onClick
});

YOu can use toggle button. For more info http://developer.android.com/guide/topics/ui/controls/togglebutton.html
<ToggleButton
android:id="#+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>
or there is another approach you can follow. you can apply style in your button.
<Button
android:id="#+id/button1"
style="#button_style/<StyleName>"
android:layout_width="200dp"
android:layout_height="126dp"
android:text="Hello" />
Create a button_style.xml file in drawable directory
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/numpad_button_bg_selected" android:state_selected="true"></item>
<item android:drawable="#drawable/numpad_button_bg_pressed" android:state_pressed="true"></item>
<item android:drawable="#drawable/numpad_button_bg_normal"></item>
</selector>

You can also define a Selector for your Button to customize highlighting,so you create a xml file then :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:state_enabled="true"
android:state_focused="false" android:drawable="#drawable/enable_notpressed" />
<item android:state_pressed="true" android:state_enabled="true"
android:drawable="#drawable/enable_pressed" />
<item android:state_pressed="false" android:state_enabled="false"
android:state_focused="false" android:drawable="#drawable/disabled" />
</selector>
then assign it to your button as background param.

use selector like:
make a new xml file in drawable folder and paste this code.and change values accordingly.
<padding
android:left="10dp"
android:top="2dp"
android:right="10dp"
android:bottom="2dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#003040"
android:endColor="#003040"
android:angle="180" />
<corners
android:radius="8dp" />
<padding
android:left="10dp"
android:top="2dp"
android:right="10dp"
android:bottom="2dp" />
</shape>
</item>
</selector>
!!happy coding!!

XML CODE:
<ToggleButton
android:id="#+id/btspeaker"
android:layout_width="100dp"
android:layout_height="70dp"
android:layout_marginRight="20dp"
android:background="#drawable/bgspeaker"
android:button="#null"
android:textOff=""
android:textOn="" />
In the drawable:
bgspeaker.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/speaker_btn_select" android:state_checked="true"/>
<item android:drawable="#drawable/speaker_btn" android:state_checked="false"/>
<item android:drawable="#drawable/speaker_btn"></item>
</selector>
In the activity:
if (v.getId() == R.id.btspeaker) {
if (btspeaker.isChecked()) {
Toast.makeText(context, "Pressed/Selected",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context,"UnSelected",
Toast.LENGTH_LONG).show();
}
}

Related

Android - Change color of Drawables

I have a selector where I set a circle as the background for the state_selected = true but I want to change the color when I click on the object. How can I do it?
This is how my drawables are set up:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#D0021B"/>
<stroke android:width="2dp" android:color="#910012" />
<size
android:width="50dp"
android:height="50dp" />
<corners android:radius="50dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/black" android:state_selected="false" />
<item android:drawable="#drawable/nav_circle" android:state_selected="true" />
</selector>
You can do it programmatically:
public static void colorDrawable(View view, int color) {
Drawable wrappedDrawable = DrawableCompat.wrap(view.getBackground());
if (wrappedDrawable != null) {
DrawableCompat.setTint(wrappedDrawable.mutate(), color);
setBackgroundDrawable(view, wrappedDrawable);
}
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void setBackgroundDrawable(View view, Drawable drawable) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
}
if you want to change the color at the moment it is pressed, you can use state_pressed.
<item android:state_pressed="true"
android:drawable="#color/pressedColor"/> <!-- pressed state -->
<item android:state_focused="true"
android:drawable="#color/pressedColor"/> <!-- focused state -->
<item android:drawable="#color/colorPrimary"/>
you can also use another drawable under the android:drawable attribute
<item android:state_pressed="true"
android:drawable="#drawable/button_solid"/>
however, if you want to change the background drawable when it is pressed, you can change the button background to a different xml drawable
button.setBackground(getDrawable(R.drawable.selectorDrawable2));
Maybe this will help you :
i=(ImageView)findViewById(R.id.image);
i.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
}
});
ImageView xml code :
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/nav_circle"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/image" />

How do i change text color when button was pressed once (Android)

what i basically wanna do is this:
When i click on the button i want its Text color to appear in a different color.
What i tried is this:
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:color="#color/red" />
<item
android:state_pressed="false"
android:color="#000" />
</selector>
and then i did use this selector as drawable on the button android:textColor
but this doesn solve it since it only changes its color while i press the button.
I want it like this:
Default: black
on click: blue
on click again: black
any ideas how to do that? :S
this is my shape for the button (if it matters):
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetBottom="-1dp"
android:insetLeft="-1dp"
android:insetRight="-1dp">
<selector>
<item android:state_pressed="false">
<shape android:shape="rectangle" >
<corners
android:radius="0dp"
/>
<solid
android:color="#color/background_grey"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="30dp"
/>
<stroke
android:width="1dp"
android:color="#ffb4b4b4"
/>
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="rectangle" >
<corners
android:radius="0dp"
/>
<solid
android:color="#color/pq_blue"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="30dp"
/>
<stroke
android:width="1dp"
android:color="#ffb4b4b4"
/>
</shape>
</item>
</selector>
</inset>
thx in advance
EDIT
so i tried to do it programatically and tied the folowing just to see if it changes color´s ..but yea..it doesn´t (it seems like my onCLick event doesnt work):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listview_item, container, false);
final Button likeButton = (Button)rootView.findViewById(R.id.btLike);
likeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String test = "tester";
if(BUTTON_STATE==BUTTON_STATE_ONCE){
likeButton.setTextColor(getResources().getColor(R.color.pq_blue));
BUTTON_STATE = BUTTON_STATE_TWICE;
}else{
likeButton.setTextColor(getResources().getColor(R.color.red));
BUTTON_STATE = BUTTON_STATE_ONCE;
}
}
});
return rootView;
}
}
NOTE: i do all tht stuff in onCreateView since im in a Fragment of my ActionBarActivity(with tabs) if im doing it in the onCreate i get a null pointer exception at findViewById ( since it searches for the ID in my mainActivity, if im right?)
so yea..any ideas?
Your textselector.xml -
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:color="#color/red" /> <!--selected text colour-->
<item
android:state_focused="true"
android:color="#color/red" />
<item
android:color="#color/blue" /> <!--unselected text colour-->
</selector>
Your button in layout.xml -
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
android:textColor="#drawable/textselector" <!-- SET textselector HERE -->
android:background="#drawable/button_color"/>
You can use this code to do it programmatically:
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ColorStateList myList=myButton.getTextColors();
int myColor=myList.getDefaultColor();
switch(myColor)
{
case Color.BLACK:
myButton.setTextColor(Color.BLUE);
break;
case Color.BLUE:
myButton.setTextColor(Color.BLACK);
break;
}
}
});
If You want to have a behaviour like:
First Click: Button text black
Second Click: Button text blue
third Click: button text black again
I don´t think it´s possible with the selector, also not with state focused. Because if any other view will be clicked, the button is not focused anymore and will loose the textcolor, goes back to default. You have to do it in a programmatically way:
First, set the default textColor to what You want: black inside Your xml. So than You have the color on no press. make a globa variabel to save the state:
private int BUTTON_STATE = 0;
private final int BUTTON_STATE_ONCE = 0;
private final int BUTTON_STATE_TWICE = 1;
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if(BUTTON_STATE==BUTTON_STATE_ONCE){
button.setTextColor(Color.BLUE);
BUTTON_STATE = BUTTON_STATE_TWICE;
}else if(BUTTON_STATE==BUTTON_STATE_TWICE){
button.setTextColor(Color.BLACK);
BUTTON_STATE = BUTTON_STATE_ONCE;
}
}
});
That´s just a possible solution, there are many ways..
EDIT
for Your code:
Create that global variables like i did in my example above, and use them in the if/else statement:
likeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(BUTTON_STATE==BUTTON_STATE_ONCE){
likeButton.setTextColor(getResources().getColor(R.color.pqBlue));
BUTTON_STATE = BUTTON_STATE_TWICE;
}else if(BUTTON_STATE==BUTTON_STATE_TWICE){
likeButton.setTextColor(getResources().getColor(R.color.pqBlack));
BUTTON_STATE = BUTTON_STATE_ONCE;
}
}
});
Try adding text_effect.xml drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#color/white" /> <!-- pressed -->
<item android:color="#color/black" /> <!-- default -->
</selector>
add this line in button control
android:textColor="#drawable/text_effect"
It will work. Enjoy:)
If you do not mandatorily need a simple Button, you could use a ToggleButton that is made for binary-state handling... With a ToggleButton your selector would look like this :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#color/red" />
<!-- Default State -->
<item android:color="#000" />
</selector>
It seems like you wanna implement something like toggle button.
Instead of button u can use toggle button.
Though if you wanna use button only then u need to do some changes in your java code as well as xml code also
Create a file def_btn.xml it will look like this..
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="0dp"
/>
<solid
android:color="#color/background_grey"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="30dp"
/>
<stroke
android:width="1dp"
android:color="#ffb4b4b4"
/>
</shape>
Create another file press_btn.xml it will look like this..
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="0dp"
/>
<solid
android:color="#color/pq_blue"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="30dp"
/>
<stroke
android:width="1dp"
android:color="#ffb4b4b4"
/>
</shape>
Inside your activity declare a private boolean variable(say isPressed) by default isPressed is false. & for default button background will be def_btn.xml
Now write following in button's onClick event.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isPressed = !isPressed;
if(isPressed){
btn.setBackgroundResource(R.drawable.def_btn);
}else{
btn.setBackgroundResource(R.drawable.press_btn);
}
}
});
That's it..

Android Onclick

How are you? I am new at Android programming. so far I have run a single app on my mobile phone using 4.1 API 16.
My question is when releasing a click event the button image in the following code should be restored to previous state.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
x = x + 1;
edittext.setText("" + x);
button.setBackgroundResource(R.drawable.buttonpressed1);
}
});
you can also use drawable touch states. an example showing color change on press:
in your button xml use android:background="#drawable/touchstates"
and touchstates.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:shape="rectangle">
<stroke android:color="#cc0099CC" android:width="1dip" />
<solid android:color="#660099CC" />
</shape>
</item>
</selector>
For normal performance you must use selector like background property of Button view
put all of this files to folder drawable
selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/bg_pressed" android:state_pressed="true" />
<item android:drawable="#drawable/br_unpressed" />
</selector>
bg_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="#dimen/circle_padding"
android:color="#android:color/transparent" />
<solid android:color="#android:color/white" />
</shape>
bg_unpressed.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="#dimen/circle_padding"
android:color="#android:color/transparent" />
<solid android:color="#android:color/black" />
</shape>
and in layout set button background android:background="#drawable/selector"
There is a full solution for you:
ImageButton guessButton;
guessButton = (ImageButton) findViewById(R.id.Knorr_Game_Guess_Button);
guessButton.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
v.setBackgroundResource(R.drawable.ic_picture1);
}
else if (event.getAction() == MotionEvent.ACTION_UP)
{
v.setBackgroundResource(R.drawable.ic_picture2);
}
return false;
}
});
It works:)
If you want to capture the release of a button, you need to use OnTouchListener
Here is an example:
yourButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//What happens when preessed
} else if (event.getAction() == MotionEvent.ACTION_UP) {
//What happens when released }
}
};
Hope this helped!
You need to use a selector. The selector needs to be a drawable file which is assigned to the background of your button. An example of a selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- focused -->
<item
android:state_focused="true"
android:drawable="#drawable/rounded_button_focused"
/>
<!--pressed -->
<item
android:state_pressed="true"
android:drawable="#drawable/rounded_button_pressed"
/>
<item
android:drawable="#drawable/rounded_button_unfocused"/>
</selector>
The selector will basically assign the correct background depending on the state of your button. If the button is pressed then it will assign the file "rounded_button_pressed" to the background of the button. The rounded_button_pressed is another drawable file for example:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:startColor="#color/WhiteSmoke"
android:endColor="#color/LightGrey"
android:angle="270"/>
<stroke
android:width="2dp"
android:color="#color/CornflowerBlue" />
<corners
android:radius="4dp"
/>
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
Hope it solves your problem

Android How to change Button Background on OnTouchListener

Hi I have a button in xml, and I am using OnTouchListener in my activity to get button press and release. But the problem is that when I press the button the background color is not changing. Where as when I extend may activity with OnClickListener the background is changing. Can any one tell what wrong with my code.
public class pushbuttonActivity extends Activity implements OnTouchListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.push_button_layout);
GPIO_0_B = (Button) findViewById(R.id.GPIO_0);
GPIO_0_B.setOnTouchListener((OnTouchListener) this);
}
public boolean onTouch(View v,MotionEvent event) {
switch(v.getId()) {
case R.id.GPIO_0 : GPIOPORT=0;
break;
default : break;
}
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//Do something on touch
} else if (event.getAction() == MotionEvent.ACTION_UP) {
//Do something in release
}
return true;
}
push_button_layout.xml
<RelativeLayout .........
.................
<Button
android:id="#+id/GPIO_0"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#drawable/round_button"
android:textStyle="bold"
android:textSize="14sp"
android:text="GPIO 0"
android:layout_marginTop="15dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="50dp"
/>
round_button.xml
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Non focused states
-->
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="#drawable/round_button_unfocused" />
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="#drawable/round_button_unfocused" />
<!-- Focused states
-->
<item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="#drawable/round_button_focus" />
<item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="#drawable/round_button_focus" />
<!-- Pressed
-->
<item android:state_pressed="true" android:drawable="#drawable/round_button_press" />
</selector>
round_button_focus.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1dp"
android:color="#FF404040" />
<corners
android:radius="6dp" />
<size android:height="40dp"
android:width="40dp"/>
<gradient
android:startColor="#FF6800"
android:centerColor="#FF8000"
android:endColor="#FF9700"
android:angle="90" />
</shape>
round_button_press.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="2dp"
android:color="#FF606060" />
<corners
android:radius="40dp" />
<gradient
android:startColor="#FF0000"
android:centerColor="#FF0000"
android:endColor="#FF0000"
android:angle="90" />
</shape>
round_button_unfocus.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="2dp"
android:color="#FF606060" />
<corners
android:radius="40dp" />
<gradient
android:startColor="#550000"
android:centerColor="#550000"
android:endColor="#550000"
android:angle="90" />
</shape>
And sorry for the lengthy post....
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
v.setPressed(true);
//doYourWorkHere();
break;
case MotionEvent.ACTION_UP:
v.setPressed(false);
//doYourWorkHere();
break;
}
return true;/* true to deactivate other listeners at the same time; false otherwise */
}
Using Ontouch you wont get the Clicked state of your button
use Onclick Coz , In onclick method Pressed state of button will be true
Actually I need to get button click and release
use this to get click and release
GPIO_0_B.setOnClickListener(new OnClickListener() {
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN) {
GPIO_0_B.setBackground(R.drawable.round_button_focus);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
GPIO_0_B.setBackground(R.drawable.round_button_unfocused);
}
}
};
For touch listner change this line GPIO_0_B.setOnClickListener(new OnClickListener() {
to
GPIO_0_B.setOnTouchListener(new OnTouchListener() {
how can I do with its id, Actually I have more than one button
Do this in onCreate():
{
Button GPIO_0_B1 =(Button) findViewById(R.id.youridfromxml);
Button GPIO_0_B1 =(Button) findViewById(R.id.youridfromxml);
GPIO_0_B1.setOnClickListener(getOnClickDoSomething(GPIO_0_B1);
GPIO_0_B2.setOnClickListener(getOnClickDoSomething(GPIO_0_B2);
}
Now
create new method (outside oncreate() method:- info for noobs)
View.OnClickListener getOnClickDoSomething(final Button Gpbot)
{
return new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(event.getAction() == MotionEvent.ACTION_DOWN) {
Gpbot.setBackground(R.drawable.round_button_focus);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Gpbot.setBackground(R.drawable.round_button_unfocused);
}
}
}
}
Just setting a layout as a background to your Button in xml will do the trick. have a xml in your drawable folder named for eg:clickedstate.xml like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
android:drawable="#drawable/default_bgnd" />
<item android:state_focused="true"
android:drawable="#drawable/new_green" />
<item android:state_pressed="true"
android:drawable="#drawable/new_green" />
<item android:state_checked="true"
android:drawable="#drawable/new_green"/>
<item android:state_selected="true"
android:drawable="#drawable/new_green" />
</selector>
In your xml just do this for your button
android:background="#drawable/clickedstate"
You can use the below code through the onclick event listener to achieve this :
StateListDrawable states = new StateListDrawable();
Drawable image_normal = //drawable of the image
Drawable image_focused = //drawable of the image
Drawable image_pressed = //drawable of the image
states.addState(new int[] {android.R.attr.state_pressed},image_focused);
states.addState(new int[] {android.R.attr.state_focused},image_pressed);
states.addState(new int[] { },image_normal);
buttonObj.setBackgroundDrawable(states);
Try with this code.
#Override
public boolean onTouch(View view, MotionEvent event) {
view.setSelected(true);
...
return true;
}

Specific radio buttons - the most simple way to set different styles for first/last buttons

I would like to achieve this specific type of radio buttons in my layout:
= different graphics for the first item, middle ones, and last one, which have different rounded corners. I can imagine doing this with different styles for the 3 types of buttons (using custom styles, stateful drawables).
I'm implementing this using custom toggle buttons. I would like to take advantage of drawable selector for using different drawables for the first and the last items, so I use:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_first="true"
android:drawable="#drawable/radio_left_act"/>
<item android:state_checked="true" android:state_last="true"
android:drawable="#drawable/radio_right_act"/>
<item android:state_checked="true"
android:drawable="#drawable/radio_middle_act"/>
<item android:state_checked="false" android:state_first="true"
android:drawable="#drawable/radio_left_inact"/>
<item android:state_checked="false" android:state_last="true"
android:drawable="#drawable/radio_right_inact"/>
<item android:state_checked="false"
android:drawable="#drawable/radio_middle_inact"/>
</selector>
But now I have a problem, that states state_first, state_last are not set automatically in my LinearLayout, so I have to set them manually every time the buttons are clicked. Is there some way, some layout, where these states are set automatically? Thank you for any help.
Found nothing special, so here is a "default" solution, with custom toggle buttons. Here are 3 different styles (put to styles.xml) for first, middle ones and last buttons:
<!-- Toggle button styles -->
<style name="CustomToggle">
<item name="android:paddingTop">9dp</item>
<item name="android:paddingBottom">9dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">0dp</item>
<item name="android:layout_weight">1</item>
</style>
<style name="FirstToggle" parent="#style/CustomToggle">
<item name="android:background">#drawable/radio_first</item>
</style>
<style name="MiddleToggle" parent="#style/CustomToggle">
<item name="android:background">#drawable/radio_middle</item>
</style>
<style name="LastToggle" parent="#style/CustomToggle">
<item name="android:background">#drawable/radio_last</item>
</style>
And a short code for activity handling the events of toggle buttons, so only 1 button is checked in the same time, and checked button is disabled:
public class AktivityActivity extends Activity
{
ArrayList<ToggleButton> toggle_buttons;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.aktivity);
initToggleButtons();
}
private void initToggleButtons()
{
toggle_buttons = new ArrayList<ToggleButton>();
toggle_buttons.add((ToggleButton) findViewById(R.id.toggle_1));
toggle_buttons.add((ToggleButton) findViewById(R.id.toggle_2));
toggle_buttons.add((ToggleButton) findViewById(R.id.toggle_3));
// Listen on all toggle buttons
for (ToggleButton toggle_button : toggle_buttons)
toggle_button.setOnCheckedChangeListener(check_listener);
// Check first toggle button
updateToggleButtons(toggle_buttons.get(0));
}
// Only one toggle can be checked, and checked button must be disabled
private void updateToggleButtons(ToggleButton checked_button)
{
for (ToggleButton toggle_button : toggle_buttons)
{
toggle_button.setChecked(toggle_button == checked_button);
toggle_button.setEnabled(toggle_button != checked_button);
}
}
// Toggle buttons change listener
OnCheckedChangeListener check_listener = new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
updateToggleButtons((ToggleButton) buttonView);
}
};
}
Maybe it can be usefull for somebody...
You should check out the Wordpress Android project. They use a "ToggleButton" that gives similar functionality. For the .xml look here. To download the complete source go here.
It wont be the same as what you want, as they just have toggle buttons, but that can most likely be adapted for your needed style of radio buttons (if it's not already built in).
The Wordpress Android project helped me learn a lot. Everything from theming, custom buttons, custom layouts, toggle buttons, xmlrpc, and more.
The simplest way I found for doing this is:
1) Extend RadioButton class as follows:
import android.content.Context;
import android.view.ViewGroup;
import android.widget.RadioButton;
public class RoundedButton extends RadioButton {
private static final int[] STATE_ONLY_ONE = new int[] {
android.R.attr.state_first,
android.R.attr.state_last,
};
private static final int[] STATE_FIRST = new int[] {
android.R.attr.state_first
};
private static final int[] STATE_LAST = new int[] {
android.R.attr.state_last
};
public RoundedButton(Context context) {
super(context);
}
#Override
protected int[] onCreateDrawableState(int extraSpace) {
ViewGroup parent = (ViewGroup) getParent();
if (parent == null) {
return super.onCreateDrawableState(extraSpace);
}
final int size = parent.getChildCount();
final boolean isFirst = (parent.getChildAt(0) == this);
final boolean isLast = (parent.getChildAt(size-1) == this);
int[] states = super.onCreateDrawableState(extraSpace + 2);
if (isFirst && isLast) {
mergeDrawableStates(states, STATE_ONLY_ONE);
} else if (isFirst) {
mergeDrawableStates(states, STATE_FIRST);
} else if (isLast) {
mergeDrawableStates(states, STATE_LAST);
}
return states;
}
}
2) Create One XML file in "res/drawable/rbtn_selector.xml" add below XML code for Radio Button background.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- First Checked -->
<item android:state_first="true" android:state_checked="true">
<shape>
<gradient
android:angle="90"
android:startColor="#color/radio_button_selected_start"
android:endColor="#color/radio_button_selected_end"
android:type="linear" />
<!--<solid android:color="#android:color/holo_blue_dark" />-->
<corners android:topLeftRadius="10dp" android:topRightRadius="10dp"/>
<stroke android:width="#dimen/radio_button_border" android:color="#color/radio_button_border_selected" />
</shape>
</item>
<!-- First Unchecked -->
<item android:state_first="true" android:state_checked="false">
<shape>
<gradient
android:angle="90"
android:startColor="#color/radio_button_unselected_start"
android:endColor="#color/radio_button_unselected_end"
android:type="linear" />
<!--<solid android:color="#android:color/holo_purple"/>-->
<corners android:topLeftRadius="10dp" android:topRightRadius="#dimen/radio_button_radius"/>
<stroke android:width="#dimen/radio_button_border" android:color="#color/radio_button_border_unselected" />
</shape>
</item>
<!-- Last Checked -->
<item android:state_last="true" android:state_checked="true">
<shape>
<gradient
android:angle="90"
android:startColor="#color/radio_button_selected_start"
android:endColor="#color/radio_button_selected_end"
android:type="linear" />
<!--<solid android:color="#android:color/holo_green_dark" />-->
<corners android:bottomLeftRadius="#dimen/radio_button_radius" android:bottomRightRadius="#dimen/radio_button_radius"/>
<stroke android:width="#dimen/radio_button_border" android:color="#color/radio_button_border_selected" />
</shape>
</item>
<!-- Last Unchecked -->
<item android:state_last="true" android:state_checked="false">
<shape>
<gradient
android:angle="90"
android:startColor="#color/radio_button_unselected_start"
android:endColor="#color/radio_button_unselected_end"
android:type="linear" />
<!--<solid android:color="#android:color/holo_red_dark"/>-->
<corners android:bottomLeftRadius="#dimen/radio_button_radius" android:bottomRightRadius="#dimen/radio_button_radius"/>
<stroke android:width="#dimen/radio_button_border" android:color="#color/radio_button_border_unselected" />
</shape>
</item>
<!-- Default Checked -->
<item android:state_checked="true">
<shape>
<gradient
android:angle="90"
android:startColor="#color/radio_button_selected_start"
android:endColor="#color/radio_button_selected_end"
android:type="linear" />
<stroke android:width="#dimen/radio_button_border" android:color="#color/radio_button_border_selected" />
<!--<solid android:color="#android:color/holo_orange_dark" />-->
</shape>
</item>
<!-- Default Unchecked -->
<item android:state_checked="false">
<shape>
<gradient
android:angle="90"
android:startColor="#color/radio_button_unselected_start"
android:endColor="#color/radio_button_unselected_end"
android:type="linear" />
<stroke android:width="#dimen/radio_button_border" android:color="#color/radio_button_border_unselected" />
<!--<solid android:color="#android:color/holo_green_light"/>-->
</shape>
</item>
</selector>
3) Create One XML file in "res/drawable/rbtn_textcolor_selector.xml" add below XML code for Radio Buttons Text selector color.(Text Color Selector xml file)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#color/radio_text_selected"/>
<item android:color="#color/radio_text_unselected"/>
</selector>
4) Set your style to the button:
4.1) Programmatically add some RoundedButton to an exixsting RadioGroup:
RoundedButton newRadioButton = new RoundedButton(this.getActivity());
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
newRadioButton.setBackgroundDrawable(this.getActivity().getResources().getDrawable(R.drawable.rbtn_selector));
} else {
newRadioButton.setBackground(this.getActivity().getResources().getDrawable(R.drawable.rbtn_selector));
}
newRadioButton.setTextColor(this.getActivity().getResources().getColorStateList(R.color.rbtn_textcolor_selector));
4.2) Xml:
<RoundedButton
android:id="#+id/bt_id_1"
android:background="#drawable/rbtn_selector"
android:textColor="#drawable/rbtn_textcolor_selector" />
5) Choose your own colors and dimensions the one I used in the example are:
<color name="radio_text_selected">#FFF</color>
<color name="radio_text_unselected">#222</color>
<color name="radio_button_selected_start">#5393c5</color>
<color name="radio_button_selected_end">#6facd5</color>
<color name="radio_button_unselected_start">#f9f9f9</color>
<color name="radio_button_unselected_end">#eee</color>
<color name="radio_button_border_selected">#2373a5</color>
<color name="radio_button_border_unselected">#aaa</color>
and:
<dimen name="radio_button_radius">10dp</dimen>
<dimen name="radio_button_border">0.7dp</dimen>

Categories

Resources