简体   繁体   中英

Add Layout Params to view programmatically - Java

I am inflating a view in my activty like this

View myView = getLayoutInflater().inflate(R.layout.my_view, my_activity_layout);

And now I want to center myView in the regular layout

I tried this

RelativeLayout.LayoutParams layoutParams =
                            (RelativeLayout.LayoutParams)myView.getLayoutParams();
                    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
                    myView.setLayoutParams(layoutParams);

But got this error

android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams

How could I center this view?

Thanks

EDIT

Here is my 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" />

Replace FrameLayout.LayoutParams instead if RelativeLayout.LayoutParams .

OR

You have to change FrameLayout to RelativeLayout in my_view.xml file

What is error here? To understand it you need to understand how view/viewgroup hierarchy is created for that refer : http://android-developers.blogspot.in/2009/03/android-layout-tricks-3-optimize-by.html

So if you go back to your view actually you have FrameLayout-->RelativeLayout-->Textview Solution Instead of use

RelativeLayout.LayoutParams layoutParams =
                        (RelativeLayout.LayoutParams)myView.getLayoutParams();
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
                myView.setLayoutParams(layoutParams);

use

FrameLayout.LayoutParams layoutParams =
                        (FrameLayout.LayoutParams)myView.getLayoutParams();
                layoutParams.addRule(//your code);
                myView.setLayoutParams(layoutParams);

or alternatively get RelativeLayout from your view

RelativeLayout rootLayout = myView.findViewById(R.id.discountView);
//And using RelativeLayout params as you have done
rootLayout.setLayoutParams(layoutParams)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM