我在代码中创建了 textView 和 editText。
TextView textview = new TextView(getActivity());
final EditText editText = new EditText(getActivity());
editText.setGravity(Gravity.CENTER);
我在 res/values/mystyle 中有样式 当我在 textView 中添加样式时,它看起来像这样:
TextView textview = new TextView(getActivity(), null, R.style.editTextStyle);
但是,什么都没有改变。 如何通过我的代码在 textView 和 editText 中添加样式。我做错了什么? 谢谢大家!
最佳答案
我们无法以编程方式设置样式:android set style in code .至少现在还没有。样式 xml 中的信息应该移动并转换为布局 xml 格式。
基本上您需要创建一个新的布局 xml,它只包含一个 View 。下面是 TextView
的示例布局:
(我的测试设置中的 layout/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>
关于java - 如何从我的代码在 textView 和 editText 中添加样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8173129/