【问题标题】:How add style in textView and editText from my code?如何从我的代码中在 textView 和 editText 中添加样式?
【发布时间】:2011-11-17 19:31:41
【问题描述】:

我在代码中创建 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 中添加样式。我做错了什么? 谢谢大家!

【问题讨论】:

标签: java android styles textview android-edittext


【解决方案1】:

我们无法以编程方式设置样式: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>

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多