添加布局参数以编程方式查看-Java
我在我的活动中膨胀一种观点,就像这样添加布局参数以编程方式查看-Java,java,android,Java,Android,我在我的活动中膨胀一种观点,就像这样 View myView = getLayoutInflater().inflate(R.layout.my_view, my_activity_layout); 现在我想在常规布局中居中显示我的视图 我试过这个 RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)myView.getLayoutParams()
View myView = getLayoutInflater().inflate(R.layout.my_view, my_activity_layout);
现在我想在常规布局中居中显示我的视图
我试过这个
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)myView.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
myView.setLayoutParams(layoutParams);
但我犯了这个错误
android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
我怎样才能使这个视图居中
谢谢
编辑
这是我的xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp" android:layout_height="250dp"
android:id="@+id/discountView" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Discount:"
android:id="@+id/discountTitleText"
android:layout_marginTop="20dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="24sp"
android:textColor="#ffffff" />
如果
RelativeLayout.LayoutParams
,则替换框架布局.LayoutParams
或
您必须在
my_view.xml
文件中将FrameLayout
更改为RelativeLayout
这里有什么错误?要理解它,您需要了解视图/视图组层次结构是如何创建的,请参阅:
因此,如果返回到视图,实际上您拥有FrameLayout-->RelativeLayout-->Textview
解决方案
代替使用
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)myView.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
myView.setLayoutParams(layoutParams);
使用
或者从你的观点中获得相对论
RelativeLayout rootLayout = myView.findViewById(R.id.discountView);
//And using RelativeLayout params as you have done
rootLayout.setLayoutParams(layoutParams)
将
RelativeLayout
更改为FrameLayout
,并将重心设置为center,因为您使用的是RelativeLayout而不是FrameLayout。因此,在布局参数中将relativelayout更改为framelaout。
RelativeLayout rootLayout = myView.findViewById(R.id.discountView);
//And using RelativeLayout params as you have done
rootLayout.setLayoutParams(layoutParams)