'How to add margins, padding, and stop text being all caps in a dynamically added toggle button?
So I've created some toggle buttons dynamically that get added to a linear layout. I am able to successfully edit some of the stylings for the buttons, but for the attributes listed in the title, I have been unsuccessful in getting any change.
This is the function creating buttons using the name from my SQLite db.
void addFilterButtons(){
Cursor cursor = my_db.readData();
if(cursor.getCount() == 0){
}else{
while(cursor.moveToNext()){
String name = cursor.getString(1);
ToggleButton filter_button = new ToggleButton(getActivity());
filter_button.setChecked(false);
filter_button.setBackgroundResource(R.drawable.toggle_bg);
filter_button.setTextAppearance(R.style.TBStyle);
filter_button.setTextOn(name);
filter_button.setTextOff(name);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
filter_button.setLayoutParams(lp);
linear_layout.addView(filter_button, lp);
}
}
}
This is the styling for toggle button.
<style name="TBStyle" parent="android:Widget.Button.Toggle">
<item name="android:background">@drawable/toggle_bg</item>
<item name="android:layout_marginStart">20dp</item>
<item name="android:padding">20dp</item>
<item name="android:textAllCaps">false</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Body1</item>
<item name="android:textSize">18sp</item>
<item name="android:textColor">@drawable/toggle_txt</item>
</style>
This is toggle_txt and toggle_bg drawables.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="@color/white"/>
<item android:color="@color/blue"/>
</selector>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/round_btn_gray"/>
<item android:drawable="@drawable/round_btn_white"/>
</selector>
Solution 1:[1]
There are a couple of ways to do this, but the easiest- put the view you want in an XML file. Then inflate the XML file. Then you don't have to do any of the tedious settings in code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vishal Vasani |
