I try to create set of TextView programmatically but a want to customize each TextView by xml style. I create TextView instances and place it into LinearLayout. In my style.xml script I add custom values for text size and color, and all work fine. But I cant't set text alignment to center by my styles.xml file.
It's my java code snippet:
import android.view.View;
public class GramophoneForm extends AppCompatActivity
{
private LinearLayout m_button_container = null;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
....
....
m_button_container = this.findViewById(R.id.gr_view_container);
List<? extends Object> ct_list = getClassificationTypes();
setObjectsList(ct_list);
}
public void setObjectsList(List<? extends Object> objects)
{
m_button_container.removeAllViews();
for(Object o : objects)
{
TextView item = new TextView(this);
item.setTextAppearance(this, R.style.selectionTextStyle);
////////////////////Is't works fine, but I want set up text alignment by xml style
item.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
////////////////////
item.setText(o.toString());
item.setTag(o);
m_button_container.addView(item);
}
}
}
My styles.xml code snippet:
<style name="selectionTextStyle" parent="@android:style/Widget.TextView">
<item name="android:layout_width">match_parent</item>
<item name="android:textSize">25dp</item>
<item name="android:textColor">#FFFF00FF</item>
<item name="android:textStyle">bold</item>
<!-- don't work -->
<item name="android:layout_centerInParent">true</item>
<!-- don't work
<item name="android:textAlignment">4</item>
-->
<!--don't work
<item name="android:textAlignment">center</item>
-->
</style>
A possible solution for your problem is to create a XML layout with a TextView with the style applied to it, and instead of creating an instance of TextView every time, inflate the layout.
XML example, lets say its named myTextViewLayout:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/selectionTextStyle" />
And in your for loop inflate it and add it to the container:
for(Object o : objects){
TextView item = (TextView)getLayoutInflater().inflate(R.layout.myTextViewLayout, null);
item.setText(o.toString());
item.setTag(o);
m_button_container.addView(item);
}
You should insert a dimension value within the style xml:
<dimen name="buttonHeight">40px</dimen>
Then you simply should reference the dimension value. So in your layout file you'll write:
android:layout_height="@dimen/buttonHeight"
将您的父属性从此parent="@android:style/Widget.TextView"
更改为此android:Widget.Material.Light.TextView
希望它能够正常工作!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.