2

I have layout with my custom view like this :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/imageView1"
    android:layout_marginLeft="30dp"
    android:layout_toRightOf="@+id/imageView1"
    android:text="Username"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textStyle="bold" />

.....

And then I want to get ViewGroup from this xml files. But the manner that I know is just inflate the layout with View Inflater like this LayoutInflater.inflate(R.id.my_layout) and the return is just View And my layout is absolutely RelativeLayout that extends ViewGroup.

How can I get My Relativelayout as ViewGroup programmatically?

mrhands
  • 1,473
  • 4
  • 22
  • 41

2 Answers2

3

After inflating typecast it into relative layout. In android every layout is view which is super class of all views and viewgroups..

you have to typecast like this..

convertView = inflater.inflate(R.layout.header, null);
RelativeLayout lyLayout=(RelativeLayout) convertView;
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
kalyan pvs
  • 14,486
  • 4
  • 41
  • 59
2

Just try this. This is an example for custom toast in android

public void showToast(Context context, String message) {
    // get your custom_toast.xml layout
    LayoutInflater inflater = getLayoutInflater();

    View layout = inflater.inflate(R.layout.toast_activity,
            (ViewGroup) findViewById(R.id.custom_toast_layout_id));
    // set a message
    TextView text = (TextView) layout.findViewById(R.id.ToastMessageTV);
    text.setText(message);
    // Toast...
    Toast toast = new Toast(context);
    // toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setView(layout);
    toast.show();
}
Ameer
  • 2,709
  • 1
  • 28
  • 44
  • The 2-parameter .inflate(..) call here was what I needed to get a custom ViewGroup to load - Thanks! Fyi, in my case this solution was necessary to resolve loading the custom FlowLayout from this demo: http://hzqtc.github.io/2013/12/android-custom-layout-flowlayout.html – Gene Bo Apr 22 '14 at 19:06