首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何以编程方式向RelativeLayout添加视图?

如何以编程方式向RelativeLayout添加视图?
EN

Stack Overflow用户
提问于 2018-05-02 06:30:14
回答 2查看 0关注 0票数 0

你能给我一个非常简单的例子,以编程方式将儿童视图添加到RelativeLayout给定的位置吗?

XML:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="107dp"
    android:layout_marginTop="103dp"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />

我不明白如何创建适当的RelativeLayout.LayoutParams实例。

EN

回答 2

Stack Overflow用户

发布于 2018-05-02 15:17:33

例子:

代码语言:javascript
复制
TextView tv = new TextView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.leftMargin = 107
...
mRelativeLayout.addView(tv, params);

RelativeLayout.LayoutParams和构造函数的文档在这里。

票数 0
EN

Stack Overflow用户

发布于 2018-05-02 15:40:22

首先,你应该给你的RelativeLayout一个id,如下:

代码语言:javascript
复制
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
TextView mTextView = new TextView(context);
mTextView.setText("Dynamic TextView");
mTextView.setId(111);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
mainLayout.addView(mTextView, params);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档