How can I make a RadioButton with overlapping text? - android

I'm adding programmatically multiple answers to a questions as RadioButtons in a RadioGroup (see code and image below).
I almost achieved it but instead of having a radio button with a text on its side (see image below), I would like to have only the text and the background.
Can I get rid of the radio button?
Or can I set my current background as the radio button (with checked/unchecked states), and add a text overlapping it?
RadioGroup answer_container = (RadioGroup) findViewById(R.id.answer_container);
while (c.isAfterLast() == false) {
RadioButton answer = new RadioButton(PCItem.this);
answer.setText(c.getString(c.getColumnIndex(DBAdapter.KEY_ANS_TEXT)));
answer.setBackgroundResource(R.drawable.btn_ans);
answer.setPadding((int)(30 * density), 0, 0, 0);
answer.setGravity(Gravity.CENTER_VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int)(775 * density), (int)(81 * density));
params.setMargins(0, (int)(20*density), 0, 0);
answer.setLayoutParams(params);
answer_container.addView(answer);
c.moveToNext();
}

You can use radioButton.setButtonDrawable(). You can also specify different drawables for each button state (including checked/unchecked) using a StateListDrawable.
To completely remove the button you can simply set it as null:
<RadioButton
android:button="#null"
...
/>
Be aware that by code radioButton.setButtonDrawable(null); doesn't work! The correct way is to set an empty StateListDrawable:
radioButton.setButtonDrawable(new StateListDrawable());
If you have more items, you can create a custom style to override the default properties of RadioButton:
<style name="CustomRadioButton" parent="#android:style/Widget.CompoundButton.RadioButton">
<item name="android:button">#null</item>
<item name="android:paddingLeft">0dp</item>
</style>

Ok, I made it using
answer.setButtonDrawable(android.R.color.transparent);
to remove the button, and using a selector as btn_ans:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="#drawable/btn_choix_unsel" />
<item android:state_checked="true" android:drawable="#drawable/btn_choix_sel" />
</selector>

Related

setOnCheckedChangeListener for every radiobutton

I have a radiogroup containing several radiobuttons whose background color is grey. When I click on a radiobutton I would need the clicked one to change background color to black, while others would keep the grey background. I know I can set OnCheckedChangeListeners for all radiobuttons like this:
if(checked) then setBackGroundColor to black;
else setBackGroundColor to grey;
but is there any more efficient way to do that? Like write just one OnCheckedChangeListener for the whole group
Create a selector -> drawable/radio_selector.xml
<?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/black" /> <!-- checked -->
<item android:state_checked="false"
android:color="#color/grey" /> <!-- unchecked -->
</selector>
And in the RadioButton view add
android:buttonTint="#drawable/radio_selector"
This works on api 21+
If you are using a lower minimum api you will need to set buttonTint in a style
<style name="radio_style" parent="Widget.AppCompat.CompoundButton.RadioButton">
<item name="buttonTint">#drawable/radio_selector</item>
</style>
and add this instead to your RadionButton
style="#style/radio_style"

Android Studio: Buttons with drawable selector displaying background wrong when applied programmatically

Im trying to change the background of some buttons programmatically with a selector.
I have two different selectors
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/palette.greyscale.lightgrey" android:state_pressed="false"></item>
<item android:drawable="#color/palette.blue.mid" android:state_pressed="true"></item>
and
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/palette.greyscale.lightgrey" android:state_pressed="false"></item>
<item android:drawable="#color/palette.orange.mid" android:state_pressed="true"></item>
which get applied programmatically depending on a boolean:
void setUI() {
int primary;
Drawable btn_color;
if (((App) getActivity().getApplication()).isGender_isMale()) {
primary = getResources().getColor(R.color.palette_blue_mid);
btn_color = getResources().getDrawable(R.drawable.button_blue);
}
else {
primary = getResources().getColor(R.color.palette_orange_mid);
btn_color = getResources().getDrawable(R.drawable.button_orange);
}
btn_speichern.setBackground(btn_color);
btn_teilen.setBackground(btn_color);
btn_offnen.setBackground(btn_color);
}
Here is one button from the fragment xml:
<Button
android:id="#+id/btn_speichern"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/button_blue"
android:text="Speichern"
android:textColor="#drawable/button_text_color"
android:textSize="20sp" />
When pressing one button another button also triggers the selector.
When changing the background in the fragment xml it works fine.
I also tried to remove android:background="#drawable/button_blue" which refers to one of the drawables ressource file, but with no sucess.
I think you can get a better picture of what my issue is by taking a look at this:
https://youtu.be/y2xKHz3bgfs
EDIT:
It seems like the selector always selects the button that is pressed and the next button with the same drawable background.
If you've got two distinct buttons you could attach onClickListeners to each and then have the onClick call send a message to your main activity indicating that the button was pressed

How to Create Square shape programmatically in android?

I am making Buttons in LinearLayout programmatically. Please see below code :
My LinearLayout in my .xml file :
<LinearLayout
android:id="#+id/outerRelativeLayout_relativeLayout2_making_dynamically"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
Programmatically i am making buttons like :
LinearLayout outerRelativeLayout = (LinearLayout) findViewById(R.id.outerRelativeLayout_relativeLayout2_making_dynamically);
Button imgBtn = new Button(MyActivity.this);
imgBtn.setId(Integer.parseInt(c.getString(0)));
LinearLayout.LayoutParams imageViewParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
imageViewParams.setMargins(0, 10, 10, 10);
outerRelativeLayout.addView(imgBtn, imageViewParams);
Here c.getString(0); means values comes from local database like 1,2,3...
This lyout looking like attached image :
On above image orange colored is LinearLayout and rounds are buttons which are programmaticaly created.
Now i want to do : when any round button clicked then a white colored square on that button should be created like to be mention which button is selected., i know about View but i cant understand how to use it to achieve what i want. Can anybody please tell me how to do it ? Hope i explain well my issue....
For Example : When Third Button(in image green round a)clicked... it should be look like this image mean to show that right now green round button is selected:
One Solution is:
Instead of doing it programatically you can have two images on the button, normal and Onclick.
So when the button is clicked the image changes.
For example:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/button" android:state_focused="true" android:state_pressed="false"/>
<item android:drawable="#drawable/buttonclick" android:state_focused="true" android:state_pressed="true"/>
<item android:drawable="#drawable/buttonclick" android:state_focused="false" android:state_pressed="true"/>
<item android:drawable="#drawable/button"/>
</selector>
Or Else:
You just have to change the coordinates programatically to make it a square.
But i prefer using the first Solution.

Change color of a radio button

I am developing an quiz based app. There will be 1 question and 4 option(radio buttons). If user select any wrong answer then I want to turn that radio button color to Red. How to do this?
Just came to show something that really help me with this:
Everyone talks about how to use the tint and how to use the colorAccent, but, this wont work on phones with API less than 21.
So, the real fix on this or at least what helped me was to use android.support.v7.widget.AppCompatRadioButton instead of RadioButton
With this on your layout, you can use:
app:buttonTint="#color/yourColor"
without getting warnings or problems about the compat of the view.
And, don't you forget about adding:
xmlns:app="http://schemas.android.com/apk/res-auto"
to your layout parent or to your widget.
Edit:
#aselims mention on a comment that there's not buttonTintin the app namespace.
So... here's my current style for this solution:
<style name="MRadioButton.Purple" parent="Widget.AppCompat.CompoundButton.RadioButton">
<item name="colorAccent">#color/youColor</item>
<item name="colorControlHighlight">#color/yourColor</item>
<item name="android:colorPressedHighlight">#color/yourColor</item>
<item name="colorPrimaryDark">#color/yourColor</item>
<item name="colorPrimary">#color/yourColor</item>
<item name="colorControlActivated">#color/yourColor</item>
</style>
The fastest thing to do is to set the buttonTint to your desired color:
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radio"
android:checked="true"
android:buttonTint="#color/your_color"/>
In your values/colors.xml put your color in this case a reddish one:
<color name="your_color">#e75748</color>
Result:
As #smashing pointed, this only will work on API level >= 21
To change RadioButton button colour programmatically, and works on api level < 21, should use AppCompatRadioButton instead of RadioButton:
(otherwise will warn setbuttontintlist requrie api level 21)
import android.support.v7.widget.AppCompatRadioButton;
AppCompatRadioButton radioButton = new AppCompatRadioButton(getActivity());
radioButton.setSupportButtonTintList(
ContextCompat.getColorStateList(getActivity(),
  R.color.single_choice_state_list));
single_choice_state_list.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#color/single_choice_checked"></item>
<item android:state_checked="false" android:color="#color/single_choice_unchecked"></item>
</selector>
This site is really good for customizing Android components in general: android-holo-colors
Just choose the radio button, make the color red, download and use it in your project!
Create a selector drawable for you radio button under drawable/radio_button.xml folder and mention all the required states for your radio button.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:state_window_focused="false"
android:drawable="#drawable/radio_button_on" />
<item
android:state_checked="false"
android:state_window_focused="false"
android:drawable="#drawable/radio_button_off" />
<item
android:state_checked="true"
android:state_pressed="true"
android:drawable="#drawable/radio_button_on_pressed" />
<item
android:state_checked="false"
android:state_pressed="true"
android:drawable="#drawable/radio_button_off_pressed" />
<item
android:state_checked="true"
android:state_focused="true"
android:drawable="#drawable/radio_button_on_selected" />
<item
android:state_checked="false"
android:state_focused="true"
android:drawable="#drawable/radio_button_off_selected" />
<item
android:state_checked="true"
android:drawable="#drawable/radio_button_on" />
<item
android:state_checked="false"
android:drawable="#drawable/radio_button_off" />
</selector>
And specify android:button="#drawable/radio_button" for your radio button
Dont forget to add the corresponding images for different states of radio button.
//get radio button reference from layout
RadioButton raPrivate = (RadioButton) layout.findViewById(R.id.radioPrivate);
//parse textColor from string hex code
int textColor = Color.parseColor("#000000");
//set textcolor to radioButton
raPrivate.setButtonTintList(ColorStateList.valueOf(textColor));
u can only assing ColorStateList objets as color for the radioButton, if u use valueOf it will only use one color.
Hope this helps :>
You can perform a backwards compatible tint on the radio button
XML:
<android.support.v7.widget.AppCompatRadioButton
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:buttonTint="#color/red"/>
Or java:
CompoundButton button = (CompoundButton) findViewById(R.id.radioButton);
CompoundButtonCompat.setButtonTintList(button, ContextCompat.getColorStateList(this, R.color.red));
Hope this helps..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
radioButton.setButtonTintList(ContextCompat.getColorStateList(mContext, R.color.colorGris));
}else {//Do something if you have a lower version}
For me its working.
add these two properties in your style this you are using in the manifest with the activity
<item name="colorControlNormal">#color/grey</item> // for state released color
<item name="colorAccent">#color/blueLogo</item> //for state pressed color
For kotlin user
Create an extension
fun RadioButton.setCircleColor() {
val colorStateList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_checked), // unchecked
intArrayOf(android.R.attr.state_checked) // checked
), intArrayOf(
Color.RED, // unchecked color
Color.GREEN // checked color
)
)
// finally set button tint list
buttonTintList = colorStateList
// optionally tint mode or tint blend
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
buttonTintBlendMode = BlendMode.SRC_IN
}else{
buttonTintMode = PorterDuff.Mode.SRC_IN
}
invalidate() // could not be necessary
}
Now call it
radioButton.setCircleColor()
done
Create an image !like this and place it in your drawable folders..
call it by,
RadioButton rb=(RadioButton) findViewById(R.id.radioButton1);
rb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
rb.setButtonDrawable(R.drawable.'you image here');
}
});
}

Android: Query regarding TableRow Selection

In my XML, I have a TableLayout with only 1 TableRow i.e. the heading. Other all rows I add dynamically setting BackgroundColor (LTGray) for TableRow & TextColor for TextViews in it . I also handle click event on each row.
private void createView(TableRow tr, TextView tv, String data, int rowId) {
tv.setText(data);
//tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setTextColor(Color.BLACK);
tv.setPadding(20, 0, 0, 0);
tr.setPadding(0, 1, 0, 1);
tr.setBackgroundColor(Color.LTGRAY);
tr.setId(rowId);
tr.setClickable(true);
tr.setOnClickListener(this);
tr.addView(tv);
}
Reg selection :
I want to change the BackgroundColor of TableRow lets say Yellow. So if 1st row is selected it bgColor should be Yellow. Then if 3rd row is selected the 1st row's color should turn to LTGray.
And if anywhere out of the Rows is clicked, then the selected Row (if at all) should also be de-selected. For this do I have to add the main layout clickListener OR make the row select again and it turns deselected ?
Can selector (state list drawable) work for both the ways or I got to handle it programmatically. What sort of Drawable should I use to setBackgroundDrawable in my Java Code to se the statelist drawable ?
I believe like other components for TableRow also onClick will also take care of onTouch. Please correct me if am wrong. As want to handle the same feature with touching the row also.
What is the best way to achieve the goal ? Any help is highly appreciated.
Do not change that in code! Use selector instead.
Taken from here:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Active state -->
<item android:state_selected="true" android:state_focused="false" android:state_pressed="false" android:drawable="#android:color/transparent" />
<!-- Inactive state-->
<item android:state_selected="false" android:state_focused="false" android:state_pressed="false" android:drawable="#android:color/transparent" />
<!-- Pressed state-->
<item android:state_pressed="true" android:drawable="#android:color/yellow" />
<!-- Selected state (using d-pad) -->
<item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="#android:color/yellow" />
</selector>
Not so thorough, but more useful answer is here
changing the selector dynamically here
Ok, than use OnFocusChangeListener. It catches obtaining and losing the focus.
onFocusChange(View v, boolean hasFocus)
Called when the focus state of a view has changed.
Thanks Friends,
I managed it handling in the code itself. Added click listener to each row addd and handle the colors of selected and non-selected row accordingly.

Categories

Resources