问题
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?
回答1:
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;
回答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();
}
来源:https://stackoverflow.com/questions/18979187/how-to-get-viewgroup-after-inflate-layout-in-android