我在remote_image_view.xml
一個自定義的RelativeLayout:定製RelativeLayouts在layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/placeholder"
/>
</RelativeLayout>
好了,現在我想將其納入main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Start Download" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="onClick" />
<Button android:text="View Downloads" android:id="@+id/button2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="showDownload" />
<ScrollView
android:layout_height="fill_parent"
android:layout_width="fill_parent"
>
<LinearLayout
android:id="@+id/lay"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical"
>
<include layout="@layout/remote_image_view" android:id="@+id/imageView1" />
<include layout="@layout/remote_image_view" android:id="@+id/imageView2"/>
<include layout="@layout/remote_image_view" android:id="@+id/imageView3"/>
<include layout="@layout/remote_image_view" android:id="@+id/imageView4"/>
<include layout="@layout/remote_image_view" android:id="@+id/imageView5"/>
<include layout="@layout/remote_image_view" android:id="@+id/imageView6"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
那就好。所以我創建了一個類RemoteImage
:
public class RemoteImageView extends RelativeLayout {
public RemoteImageView(Context context) {
super(context);
}
public void init(RelativeLayout.LayoutParams layoutParams) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.remote_image_view, this);
setLayoutParams(layoutParams);
}
}
並且出現了一個很常見的問題。 我不會寫如下代碼:
RemoteImageView rm1 = (RemoteImageView)findViewById(R.id.imageView1);
因爲我會得到異常:
java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to com.dmact.remoteimage.RemoteImageView
所以我應該動態創建的RemoteImageView
一個實例,然後塗抹一些LayoutParams
它。有沒有辦法做到這一點?我想在XML中進行佈局,而不是在代碼中。
+1 you beet me ... –
謝謝,夥計們!我甚至不知道這是可能的... – efpies
現在,IDEA向我顯示錯誤:'無法執行渲染:java.lang.ClassCastException:com.android.layoutlib.bridge.MockView無法轉換爲android.view.ViewGroup'。如果從'RemoteImageView'中刪除'ImageView',它會顯示'Missing class com.dmact.remoteimage.RemoteImageView' – efpies