【问题标题】:Android: Is it possible to make a copy of a View?Android:是否可以制作 View 的副本?
【发布时间】:2012-02-03 01:00:07
【问题描述】:

我正在开发的应用程序需要显示配置文件的 Horizo​​ntalScrollView 的动态布局。配置文件只是一个带有图片和一些文本的 RelativeLayout。由于我从数据文件中获取数据,因此我需要为每个配置文件创建一个相对布局。起初,我在 for 循环中以编程方式创建了每个 RelativeLayout,然后将其添加到父视图中。这行得通,但我不想这样做。我想根据设备的屏幕大小等使用不同的布局文件。

然后我想。好吧,如果我有一个只有一个配置文件的布局怎么办?我的代码可以使用findViewById() 获得一个配置文件,然后根据它创建新的配置文件!换句话说:

    // get the layout
    profileLayout = (LinearLayout) findViewById(R.id.profileLayout);        

    // get the first profile in the layout
    originalProfile = (RelativeLayout) findViewById(R.id.profile1);

    // make copy of profile
    temporaryProfile = originalProfile;

    // make changes to the this profile and add it back
    profileLayout.addView(temporaryProfile);

当然,这是行不通的,因为这是 java 而temporaryProfile 现在是对originalProfile 的引用。那么有没有办法复制这个RelativeLayout呢?我知道 LayoutInflater,但我仍然不明白它是如何工作的。还有Object.clone()

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    没那么多。听起来您的特殊情况可能会受益于某种 ListView 和适配器(有关信息,请参阅this 等资源)。如果不是,那么 LayoutInflater 最好的答案,因为它完全符合您的要求。获取一个之后,您可以使用它来“膨胀”您在 XML 布局文件中定义的任何视图,并使用它做任何您想做的事情。

    Here's关于充气机的精彩讨论。

    【讨论】:

      【解决方案2】:

      您可以使用新的上下文复制您的充气机。 Layout Inflater - Android Developers

      【讨论】:

        【解决方案3】:

        为什么不简单地在 xml 文件中使用包含您想要的布局。

        【讨论】:

          猜你喜欢
          • 2020-03-20
          • 1970-01-01
          • 1970-01-01
          • 2013-08-14
          • 1970-01-01
          • 1970-01-01
          • 2012-10-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多