我正在处理的应用程序需要一个动态布局,显示配置文件的HorizontalScrollView。配置文件只是一个带有图片和一些文本的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()
。
答案 0 :(得分:8)
不是那么多。听起来像您的特定情况可能会受益于某种类型的ListView和适配器(请参阅this等资源获取信息)。如果没有,那么LayoutInflater 是最好的答案,因为它正是你想要的。获取一个,然后您可以使用它来“膨胀”您在XML布局文件中定义的任何视图,并随意执行任何操作。
Here's对inflater进行了很好的讨论。
答案 1 :(得分:2)
您可以使用新的上下文制作充气机的副本。 Layout Inflater - Android Developers
答案 2 :(得分:0)
为什么不在xml文件中使用include来获得所需的布局。