繁体   English   中英

如何在Android中扩充布局后获取ViewGroup?

[英]How to get ViewGroup after inflate layout in Android?

我有自定义视图的布局,如下所示:

<?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 LayoutInflater.inflate(R.id.my_layout)布局,就像这个LayoutInflater.inflate(R.id.my_layout) ,返回只是View而我的布局绝对是扩展ViewGroup RelativeLayout

如何以编程方式将My Relativelayout作为ViewGroup?

在将类型转换为相对布局之后。 在android中,每个布局都是视图,它是所有视图和视图组的超类。

你必须像这样打架..

convertView = inflater.inflate(R.layout.header, null);
RelativeLayout lyLayout=(RelativeLayout) convertView;

试试吧。 这是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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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