【问题标题】:How to add elements to the current open activity Android如何将元素添加到当前打开的活动 Android
【发布时间】:2015-10-27 13:05:06
【问题描述】:

我是 android 新手,我正在尝试了解如何添加元素以打开活动布局并立即显示更改。 是否可以通过添加addView?我试过了,没有成功。

    TextView sv = new TextView(this);
    TextView b = new TextView(this);
    sv.setGravity(Gravity.CENTER_VERTICAL);
    b.setText("ggg");
    sv.setText("asdsadasdasdasdasdas");

    RelativeLayout ll = new RelativeLayout(this);
    ll.addView(sv);
    ll.addView(b);
    this.setContentView(ll);

这样删除之前的一切

【问题讨论】:

  • 向我们展示您的尝试。
  • TextView sv = new TextView(this); TextView b = new TextView(this); sv.setGravity(Gravity.CENTER_VERTICAL); b.setText("ggg"); sv.setText("asdsadasdasdasdasdas");相对布局 ll = new RelativeLayout(this); ll.addView(sv); ll.addView(b); this.setContentView(ll);
  • @TzurielYamin 首先不要在评论中发布代码,请有问题地对其进行编辑,并且您的代码似乎错误,因为首先您必须从布局中获取相对布局引用或将 relativelayout 设置为您的 setcontentview()而不是布局
  • 获取适当的帮助上传您的布局文件

标签: java android android-activity mobile


【解决方案1】:

如果您想将元素添加到预先存在的布局中,则不应创建新的 RelativeLayout。您应该像这样创建对现有 RelativeLayout 的引用。

TextView textView = new TextView(this);
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setText("New TextView");

RelativeLayout layout = (RelativeLayout)findViewByID(R.id.layout_id);
layout.addView(textView);

将 layout_id 替换为您的 XML 布局的 id。

【讨论】:

  • TNX 人。我还有一个问题,我可以给新的 textview ID 吗?以及如何相对于其他元素设置它? TNX
  • 使用textView.setId(int ID) 设置ID。参考The android reference的表格包含了调整XML属性(ctrl+f XML属性)的java方法。
  • TNX。由于某种原因,当我尝试插入数字时出现错误
【解决方案2】:

是的,您可以在运行时添加。从 inflate 函数获取 View 实例并添加到您在活动中的布局中。如果您遇到问题,请向我展示您的代码。

【讨论】:

  • TextView sv = new TextView(this); TextView b = new TextView(this); sv.setGravity(Gravity.CENTER_VERTICAL); b.setText("ggg"); sv.setText("asdsadasdasdasdasdas");相对布局 ll = new RelativeLayout(this); ll.addView(sv); ll.addView(b); this.setContentView(ll);
  • setLayoutParam 以相对布局和背景颜色填充父级。因为我认为它已添加,但您看不到。
【解决方案3】:

setContentView 替换您的布局,addContentView 会添加到当前布局中。 http://developer.android.com/reference/android/app/Activity.html#addContentView(android.view.View, android.view.ViewGroup.LayoutParams)

但这不是这样做的方法。

使用一些根布局(例如 LinearLayout)定义您的基本布局,在初始 setContentView 之后,执行 findViewById 以获取对该布局的引用,然后您可以实时向其添加视图

代码:

onCreate(...) {
   setContentView(R.layout.my_initial_layout);
   root = (LinearLayout) findViewById(R.id.my_root_view);
}

whenSomethingHappens() {
   TextView tv = new TextView(this);
   tv.setText("Hello!");
   root.addView(tv);
}

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多