java - 如何以编程方式设置 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" />
解决方案
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");
推荐阅读
- ios - 如何在 ARKit 1.5 上获取镜头位置
- google-calendar-api - 导出日历时不保留事件颜色设置
- django-rest-framework - 尽管权限类 Angular 5,django rest 框架 JWT 返回匿名用户
- java - Maven 错误:无法找到或加载主类(pom.xml 文件)
- java - 告诉 IntelliJ 生成代码,其中字段(成员变量)以 `this.` 开头
- jquery - 将每个输入附加到壁橱表单中,对我不起作用
- entity-framework - 在 EF 核心中获取正在进行的事件
- java - 如何在 java.util 程序中传递基于类的数组列表的参数
- c# - Vue 组件不呈现...呈现为空 HTML 注释
- c++ - 在 OSX 上从源代码构建 GIMP 2.10 在“gimp-debug-tool-2.0”上失败