【问题标题】:Duplicate a view programmatically from an already existing view以编程方式从现有视图复制视图
【发布时间】:2016-10-27 00:19:11
【问题描述】:

我正在尝试以下代码并收到错误,因为没有定义这样的构造函数。

View v = new View(findViewById(R.id.divider));

有什么简单的方法可以将一个视图复制到另一个视图中吗?

【问题讨论】:

标签: android android-view


【解决方案1】:

显然您无法克隆这些答案所述的视图:

How do I clone a View?

How to create Clone-Duplicate View?

如果您从 XML 中扩充第一个视图,那么要走的路似乎也是从 XML 中扩充第二个视图。

要从 XML 扩展您的视图,请将其放入一个额外的布局文件中,例如“文本视图.xml”

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />

然后,在你的 onCreate() 中从 XML 膨胀它:

View view = LayoutInflater.from(this).inflate(R.layout.textview, null);
myLayout.addView(view);

【讨论】:

  • 如果我们在 onCreate() 之外的函数中需要它怎么办?有什么想法吗?
  • @SyedHissaan 创建一个全局变量来保存您的上下文:Context contextApp;。然后在 OnCreate 中填充变量:contextApp = this。在 OnCreate 之外的函数中,您通常会在其中放置“this”,而不是放置“contextApp”。
  • 画布库怎么办,xml 不存在?
猜你喜欢
  • 1970-01-01
  • 2013-04-15
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
相关资源
最近更新 更多