2013-09-24 30 views
1

我的佈局,這樣我的自定義視圖:如何在Android的充氣佈局之後獲取ViewGroup?

<?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。但我知道的方式只是膨脹的視圖Inflater的佈局這樣的LayoutInflater.inflate(R.id.my_layout)和返回只是View而我的佈局絕對RelativeLayout延伸ViewGroup

如何以編程方式將我的Relativelayout作爲ViewGroup?

回答

2

將typecast擴展爲相對佈局後。在Android的每一個佈局圖,該超類的所有意見和viewgroups ..

,你必須強制轉換這樣的..

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

剛剛嘗試這一點。這是一個在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(); 
} 
+0

這裏的2參數.inflate(..)調用是我需要的一個自定義ViewGroup加載 - 謝謝! Fyi,在我的情況下,這個解決方案對於從這個演示中加載自定義FlowLayout是必要的:http://hzqtc.github.io/2013/12/android-custom-layout-flowlayout.html – gnB