布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/iv_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/first_registration_relativelayout_on" />
<TextView
android:id="@+id/tv_Textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/test"
/>
</RelativeLayout>
方法的实现
public class ImageText extends LinearLayout{
<span style="white-space:pre"> </span>private ImageView imageView;
<span style="white-space:pre"> </span>private TextView textView;
<span style="white-space:pre"> </span>public ImageText(Context context) {
<span style="white-space:pre"> </span>super(context);
<span style="white-space:pre"> </span>// TODO Auto-generated constructor stub
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public ImageText(Context context, AttributeSet attrs) {
<span style="white-space:pre"> </span>super(context, attrs );
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
<span style="white-space:pre"> </span>View view = inflate.inflate(R.layout.item_widget, null);
<span style="white-space:pre"> </span>//别忘了,加载完布局后,从加载后的<span style="color:#ff0000;">view</span>中获得控件Id,要不就是<span style="color:#ff0000;">空指针异常</span>
<span style="white-space:pre"> </span>imageView = (ImageView)view.findViewById(R.id.iv_imageview);
<span style="white-space:pre"> </span>textView = (TextView) view.findViewById(R.id.tv_Textview);
<span style="white-space:pre"> </span><span style="color:#ff0000;">addView(view);//许多人的自定义方法没有这一行,如果没有这一行的话,控件加载不了布局里面的,显示为空白;</span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>public void setImageResource(int resId){
<span style="white-space:pre"> </span>imageView.setImageResource(resId);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void setImageText(String text){
<span style="white-space:pre"> </span>textView.setText(text);
<span style="white-space:pre"> </span>}
}
<com.example.customwidget.view.ImageText
android:id="@+id/it_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>