我们无法以编程方式设置样式:android set style in code。至少现在还没有。我应该将样式 xml 中的信息移动并转换为布局 xml 格式。
基本上你需要创建一个新的布局xml,它只包含一个视图。这是TextView 的示例布局:
(我的测试设置中的布局/edit_text_style.xml)
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#000033"
android:textColor="#00aa00"
android:typeface="monospace"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
然后应该使用getLayoutInflater() 在Activity 代码中创建TextView。这是示例代码:
(MainActivity.java 在我的测试设置中使用 layout/main.xml。)
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout root = (LinearLayout) findViewById(R.id.root);
TextView test = (TextView) getLayoutInflater().inflate(R.layout.edit_text_style, null); // Magic!
test.setText("Ah, hello World..."); // Remove this if you set text in the xml
root.addView(test); // Bang!
这也是我的测试设置中的 main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="@+id/test"
android:text="Absolutely meaningless and mostly harmless text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>