【发布时间】:2014-04-22 00:35:25
【问题描述】:
我有一个基本的应用程序正在运行,但现在我专注于格式化应用程序,并且遇到了我想要的东西布局的困难。
我有一个图像列表,用户可以使用下一个按钮从一个图像切换到下一个图像。图像和下一个按钮都以编程方式添加到页面(我清除布局中的任何内容,然后添加 ImageView 和 Button)。现在,我不是将它们放在另一个之上,而是尝试将它们并排放置,因此图像将占据大部分空间,然后下一个按钮将位于其右侧。
查看文档,我倾向于使用 RelativeLayout 来完成此操作。但是,我在以编程方式使用 RelativeLayouts 时遇到了一些问题。
Activity.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout
android:orientation="vertical"
android:id="@+id/activity_training_package_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="com.example.xxx.PackageActivity"
tools:ignore="MergeRootFrame">
</RelativeLayout>
</ScrollView>
尝试以编程方式添加按钮:
public void addNextButton(final int currentFile, final RelativeLayout layout) {
Button next = new Button(this);
next.setWidth(100);
int id = layout.getChildAt(0).getId(); // the image is the only thing there
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.RIGHT_OF, id);
next.setLayoutParams(lay);
next.setText("NEXT >>");
next.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
showNextFile(currentFile, layout);
}
//layout.setLayoutParams(lay);
layout.addView(next);
...
我只是想知道我应该为此设置哪个 LayoutParams,布局的 LayoutParams 还是视图的?当我尝试将其设置为布局时,我得到一个强制转换异常(由于某种原因,它需要 FrameLayout.LayoutParams,而不是 RelativeLayout.LayoutParams)。
有人可以指出正确的方向来弄清楚如何使用布局吗?我似乎找不到解释我应该设置哪些 LayoutParams 的资源。
TL;DR 如何以编程方式使用 RelativeLayouts 和 LayoutParams?
【问题讨论】:
-
你能把你得到的
Exception的logcat贴出来吗?