This is inside a custom view class that extends RelativeLayout not inside an Activity or Fragment.
My RadioGroup exists in my xml and I'm trying to dynamically add RadioButtons to it. The only time I've seen it where the mutual exclusivity does not work, is if you do not add an id but I am here. What happens is when I tap a radio button more than 1 button is selected at a time. What am I missing here?
for(String buttonName : mButtonNames){
RadioButton radioButton = new RadioButton(getContext());
radioButton.setId(ViewCompat.generateViewId() );
radioButton.setText(buttonName);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.weight = 1;
radioButton.setLayoutParams(layoutParams);
radioButton.setBackground(mRadioBckgrdDrawable);
radioButton.setButtonDrawable(null);
radioButton.setGravity(Gravity.CENTER);
radioButton.setTextSize(mTextSize);
radioButton.setTextColor(mTextColor);
mRadioGroup.addView(radioButton);
}
Background drawable:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected-->
<item android:drawable="#drawable/two_stage_toggle_button_on"
android:state_checked="true" />
<!-- When not selected-->
<item android:drawable="#drawable/two_stage_toggle_button_off"
android:state_checked="false"/>
</selector>
Related
I would to create a number of radio button dinamically in a fragment, I only have problem with style. If I put radiobutton code in the xml file, default style is applied correctly, but when I create radiobutton through a function I see different style!
XML
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:animationCache="false">
<RadioButton
android:text="RadioButton 1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radioButton3" />
<RadioButton
android:text="RadioButton 2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radioButton4" />
</RadioGroup>
RESULT
JAVA CODE
This code is put in onCreateView in the fragment
public void addRadioButton(Context ctx,int num){
RadioGroup radioGroup= (RadioGroup) alertInflatedView.findViewById(R.id.radiogroup);
for (int i = 1; i <= num; i++) {
RadioButton radioButton = new RadioButton(ctx);
radioButton.setId(1+i);
radioButton.setText("Radio " + radioButton.getId());
radioButton.setTextColor(getResources().getColor(R.color.black));
radioGroup.addView(radioButton);
}
}
RESULT
As you can see radio buttons have different style, someone could help me, if is possibile, to apply default style programmatically?
you have to create style on drawable or style.xml, as your requirement.
drawable/null_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="#android:color/transparent" />
</selector>
Set each button to use it (and to center the text) like this (R.drawable.null_selector is selector XML):
Now, In your Activity, you must be implement such style.
RadioButton radioButton = new RadioButton(ctx);
radioButton.setText(Integer.toString(i));
radioButton.setGravity(Gravity.CENTER);
radioButton.setButtonDrawable(R.drawable.null_selector);
I think, this will help you for implementing custom style in Radio Button.
Thanks Dharma, I followed your suggestion, changing something, and I solved!
JAVA CODE
public void addRadioButton(Context ctx,int num){
RadioGroup radioGroup= (RadioGroup) alertInflatedView.findViewById(R.id.radiogroup);
RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.MATCH_PARENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
for(int i=0; i<num; i++){
RadioButton radioButton = new RadioButton(ctx);
radioButton.setId(1+i);
radioButton.setText("Radio"+i);
radioButton.setTextSize(16);
radioButton.setTextColor(getResources().getColor(R.color.black));
radioButton.setButtonDrawable(R.drawable.radio_button_selector);
radioButton.setPadding(80,0,0,0);
radioButton.setGravity(Gravity.CENTER_VERTICAL);
radioButton.setLayoutParams(layoutParams);
radioGroup.addView(radioButton);
}
}
XML RADIO BUTTON SELECTOR with checked and unchecked button image
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false" android:drawable="#drawable/unchekedradiobutton" />
<item android:state_checked="true" android:drawable="#drawable/checkedradiobutton" />
<item android:drawable="#drawable/unchekedradiobutton" /> <!-- default -->
Use an Inflater instance to inflate a custom layout and easily get a custom Radiobutton
private RadioButton createCustomRadioButton(Context context){
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.radio_button,null);
RadioButton radioButton = (RadioButton) v.findViewById(R.id.radio_button);
radioButton.setText("It Works!");
((ViewGroup)radioButton.getParent()).removeView(radioButton);
return radioButton;
}
radio_buttom.xml
<RadioButton
android:id="#+id/radio_button"
style="#style/radio"
android:background="#drawable/style_line" />
style.xml
<style name="radio">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">30dp</item>
<item name="android:layout_marginRight">30dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:layout_marginBottom">10dp</item>
<item name="android:padding">10dp</item>
<item name="android:drawablePadding">5dp</item>
<item name="android:textColor">#color/whiteColor</item>
<item name="android:textColorHint">#color/hintColor</item>
<item name="android:editTextColor">#color/whiteColor</item>
</style>
by Ubirajara (México)
Programmatically, I recommend setting a ColorStateList to each radio button in the loop like this:
radioButton.setButtonTintList(getRadioButtonColors());
Then
private ColorStateList getRadioButtonColors() {
return new ColorStateList (
new int[][] {
new int[] {android.R.attr.state_checked}, // checked
new int[] {android.R.attr.state_enabled} // unchecked
},
new int[] {
Color.GREEN, // checked
Color.BLUE // unchecked
}
);
}
Where android.R.attr.state_checked defines the color for the checked button (green) and android.R.attr.state_enabled defines the color for unchecked buttons (blue).
Personally I think this is a better solution because it's more concise than creating styles and other dependencies elsewhere in the codebase. Whenever possible use the most concise and efficient approach.
I dynamically generate TextViews which work like buttons. Now i want to highlight them when they get pressed. Something like change Text color or background color.
I have tried to use selector, but it doesn't work.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="#ffffff"/>
<item android:state_pressed="true" android:state_enabled="false" android:color="#ffffff" />
</selector>
Here my loop for creating the TextViews.
int z = 0;
for (MOKGenericDataItem d : data) {
if (d.getButtonText() != null) {
final int pagePosition = z;
TextView btn = new TextView(getActivity());
btn.setId(z);
final int id_ = btn.getId();
btn.setText(d.getButtonText());
btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
btn.setGravity(Gravity.CENTER);
mLineareLayoutViewPagerButtons.addView(btn);
btn1 = ((TextView) view.findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mViewPager.setCurrentItem(pagePosition,false);
}
});
}
z++;
}
First of all your this line is creating ambiguity as you are taking a variable name as btn1 (which is relating it to button)and you are taking a reference of TextView,
btn1 = ((TextView) view.findViewById(id_));
Anyways,Go step by step,
create an xml like label_bg.xml like the following in the drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pressed_color"
android:state_pressed="true" />
<item android:drawable="#drawable/normal_color" />
</selector>
In values folder create another xml like the following,named as labelcolors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="pressed_color">#7ec0ee</drawable> <!--custom color for pressed state -->
<drawable name="normal_color">#00FFFFFF</drawable> <!--transperent color for normal state -->
</resources>
Now set the background of the label as label_bg.xml
<TextView
android:id="#+id/yourlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="760dp"
android:layout_marginTop="515dp"
android:background="#drawable/label_bg" <!--like this-->
android:text="LabelText"
android:textSize="20dp" />
as you are dynamically adding the views so you need to set the background for your each textView programatically .For that call setBackgroundResource() on the textview object created and set label.xml as background
You need to create a class implements with OnTouchListener and Detect touch Motin. ACTION_DOWN, change text color and ACTION_UP change it's default color according to your requirement.
Code:
public class CustomTouchListener implements View.OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
((TextView) view).setTextColor(0xFFFFFFFF); // white
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
((TextView) view).setTextColor(Color.parseColor("#4a4a4a")); // lightblack
break;
}
return false;
}
}
Now set TouchListener using
textView.setOnTouchListener(new CustomTouchListener());
For some reason the text color of the selected item in my spinner is white. Here's the code for the Activity:
spinner = (Spinner) findViewById(R.id.spinner_categories);
arr_list_categories = manager.get_all_categories();
arr_list_categories_names = new ArrayList<String>();
// Loop through the Categories array
for (int i = 0; i < arr_list_categories.size(); i++)
{
Category curr_category = arr_list_categories.get(i); // Get the Category object at current position
arr_list_categories_names.add(curr_category.getCategory_name()
.toString()); // Add the name of the Category to the Names Array
}
// Setting the Adapter, to display retrieved data in the Spinner
adapter=new ArrayAdapter<String> (this, R.layout.simple_spinner_item, arr_list_categories_names);
// Setting the display source for the Spinner View
adapter.setDropDownViewResource(R.layout.simple_spinner_item);
// Populating the Spinner
spinner.setAdapter(adapter);
// Registering for On Item Selected listener
spinner.setOnItemSelectedListener(spinnerListener);
And here's the XML of simple_spinner_item:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="5dip"
android:textColor="#FF0000"
android:textSize="20sp" />
The dropdown items appear in red, but not the selected item. I tried to change the textColor in XML to selector: android:textColor="#drawable/spinner_text_color_selector" and created this selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#FF0000"/><!-- pressed -->
<item android:state_focused="true" android:color="#FF0000"/><!-- focused -->
<item android:state_selected="true" android:color="#FF0000"/>
<item android:state_activated="true" android:color="#FF0000"/>
<item android:color="#FF0000"/><!-- default -->
</selector>
But the selected item's text color was still white. So I tried to do this in OnItemSelectedListener:
TextView selected_tv = (TextView) parent.getChildAt(0);
selected_tv.setTextColor(Color.BLUE);
Still white...
Why is it happening and how do I fix it? Thank you!
TextView selected_tv = (TextView) parent.getChildAt(0);
selected_tv.setTextColor(Color.BLUE);
In this code, change in first line like this (Use TextView's id):
TextView selected_tv = (TextView) parent.findViewById(R.id.selected_tv);
selected_tv.setTextColor(Color.BLUE);
I have a ListView with a TextView in each row. I have a default color.xml with is set in the row.xml
I have different colors for different states
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- pressed -->
<item
android:color="#ffffff"
android:state_pressed="true"/>
<!-- focused -->
<item android:state_selected="true"
android:color="#8b8989"/>
<!-- default -->
<item android:color="#ffffff"/>
</selector>
This works like a charm. But when Im trying to change the color for some rows in code, this doesn't seem to work. The second_color.xml looks just the same, but with different colors. The color is changed, but for the other states (not default) nothing changes.
I change the color like this:
TextView tl = (TextView) v.findViewById(R.id.textlabel);
tl.setTextColor(getContext().getResources().getColor(R.color.second_color));
Solved it!
In order to set this in code it's required to create a ColorStateList.
ColorStateList cl = null;
try {
XmlResourceParser xrp = getResources().getXml(R.color.live_color);
cl = ColorStateList.createFromXml(getResources(), xrp);
} catch (Exception ex) {}
if(cl != null){
tl.setTextColor(cl);
}
if your xml file is saved at /res/row.xml then you reference it with R.color.row
TextView tl = (TextView) v.findViewById(R.id.textlabel);
tl.setTextColor(R.color.row);
How to put dynamic button using xml.
i want to fetch the position of button from the xml and place them in screen.
What do you mean by dynamic?
create an xml file called filename.xml, put this in. Change the drawables where necessary. That is bt_return and bt_returnpress
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/bt_return" android:state_pressed="false" />
<item android:drawable="#drawable/bt_returnpress" android:state_pressed="true" />
<item android:drawable="#drawable/bt_return" android:state_focused="false" />
<item android:drawable="#drawable/bt_returnpress" android:state_focused="true" />
</selector>
Then assign the filename.xml to the background of the dynamic button u want.
If I'm not wrong you want to add a button dynamically in your view pragmatically?
If you have to get the parent view in which you want to add button, then create a button and add.
For example you have a LinearLayout already defined.
LinearLayout controls =
(android.widget.LinearLayout)
findViewById(R.id.id_of_your_layout);
Button button = new Button(context);
controls.add(button);
that's it.
In your xml layout file:
<LinearLayout android:id="#+id/layoutbase"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
Then in your code:
LinearLayout layoutbase =
(LinearLayout) findViewById(R.id.layoutbase);
LinearLayout.LayoutParams mylayout = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button mybutton = new Button(this);
mybutton.setText("Button!");
mybutton.setTag("mybutton");
mybutton.setId(999);
mybutton.setLayoutParams(mylayout);
mybutton.setOnClickListener(this);
You also need to implement the OnClickListener:
#Override
public void onClick(View v) {
String tag = (String) v.getTag();
if (tag == "mybutton") {
// do some stuff
}
}
OR
#Override
public void onClick(View v) {
switch (v.getId()) {
case 999:
// do some stuff
break;
default:
}
}