【问题标题】:How to set Textview's attributes programmatic way?如何以编程方式设置 Textview 的属性?
【发布时间】:2019-03-27 12:30:29
【问题描述】:

如何通过 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" />

【问题讨论】:

  • 你为什么要这样做? LayoutInflater 有什么问题?
  • 可以在TextView的Java类中创建一个对象并使用setText()方法。
  • 对不起,我没看懂:Programmatic way from XML code
  • 如何动态设置属性,所以我问这个问题
  • 如何从java代码动态设置android中textview属性layout_weight,layout_margin的值

标签: java android xml android-layout


【解决方案1】:
    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");

【讨论】:

  • 抱歉阅读了更新的答案。您需要在参数上使用 setMargins() 而不是 textview。
【解决方案2】:

供您了解的基本信息: 您在 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));

【讨论】:

  • 本程序不包括保证金
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-28
    • 2021-06-22
    • 2023-01-03
    • 2013-02-07
    • 2021-05-20
    相关资源
    最近更新 更多