首页 > 解决方案 > 如何以编程方式设置 Textview 的属性?

问题描述

如何从 XML 代码以编程方式设置 Textview 的属性值?

  <TextView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_margin="3dp"
    android:layout_weight="0.5"
    android:background="@color/colorPrimary"
    android:gravity="center"
    android:text="text1" />

  <TextView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_margin="3dp"
    android:layout_weight="0.5"
    android:background="@color/colorPrimary"
    android:gravity="center"
    android:text="text2" />

标签: javaandroidxmlandroid-layout

解决方案


    TextView textView = new TextView(this);

    //set layout weight like this where 0.5 f is layout_weight
    LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.5f); 
        params.setMargins(10, 0, 5, 0);
        textView.setLayoutParams(params);
        textView.setBackgroundColor(Color.WHITE);
        textView.setGravity(Gravity.CENTER);
        textView.setText("Text");

推荐阅读