繁体   English   中英

如何以编程方式设置Textview的属性?

[英]How to set Textview's attributes programmatic way?

如何从 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" />
    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");

您的知识的基本信息:您在 XML 布局中采用的每个视图实际上都是您正在采用的类对象。 是的,所以这些类是 LinearLayout、TextView、Button 等。

现在如上所述这些是类,以便以编程方式访问它们,您可以创建特定视图的对象,访问和应用可用方法:

例如:

TextView textView = new TextView(this);
textView.setText("Hello World!");
textView.setId(randomId);
textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

如果你想改变宽度、高度、重力……你必须使用你的 textView 的 LayoutParams 对象

https://developer.android.com/reference/android/view/ViewGroup.LayoutParams

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM