我的自定义视图布局如下:
<?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" />
.....
然后我想从这个xml文件中获取ViewGroup。但我知道的方式只是使用View Inflater扩展布局,例如LayoutInflater.inflate(R.id.my_layout)
,返回只是View
我的布局绝对是RelativeLayout
,扩展了ViewGroup
。< / p>
如何以编程方式将My Relativelayout作为ViewGroup?
答案 0 :(得分:2)
将类型转换为相对布局。在android中,每个布局都是视图,它是所有视图和视图组的超类..
你必须像这样进行类型转换..
convertView = inflater.inflate(R.layout.header, null);
RelativeLayout lyLayout=(RelativeLayout) convertView;
答案 1 :(得分:2)
试试吧。这是android
中自定义toast的示例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();
}