我正在尝试将自定义 View 置于相对布局的中心。该图像会旋转,因此它需要位于布局的中心,这样它就不会超出布局范围。现在它显示在左上角。这是我的代码:
container = (RelativeLayout) findViewById(R.id.lay_container);
bmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.charlie_sheen);
rotate_view = new RotationView(this, bmap);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
rotate_view.setLayoutParams(params);
container.addView(rotate_view);
这是我的相对 xml 布局
<RelativeLayout
android:id="@+id/lay_container"
android:layout_width="200dip"
android:layout_height="200dip"
android:layout_alignParentRight="true"
android:layout_below="@+id/txt_1"
android:layout_marginRight="45dp"
android:layout_marginTop="56dp"
android:padding="10dip" />
你有什么想法吗?我知道这个问题可能有一个简单的解决方案,但我似乎找不到答案。将 LayoutParameter 设置为 center 应该使 View 在布局中居中,对吗?
预先感谢您的任何帮助或建议
最佳答案
总的来说,添加自定义 View 的代码看起来是正确的。这可能是一个薄弱的建议,但要排除 View 自定义可能引起的任何问题,您可以尝试通过以下两种方式之一修改代码。
选项1:使用显式形式的addRule()
,即
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
选项 2:使用显式形式的 addView()
并且不要在 View 本身上设置参数,即
//Omit the line above this one
container.addView(rotate_view, params);
除此之外,也许对自定义 View 有一些了解,特别是它如何测量自身(它不是试图填充父 View ,是吗)?
HTH
关于android - 使用 LayoutParams 将自定义 View 在relativelayout中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9539935/