Android自助餐之自定义控件(一)从layout自定义控件

Android自助餐之自定义控件(一)从layout自定义控件

查看全套目录

从layout自定义控件

  1. layout中新建一个layout

    <?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" >
     <TextView
         android:id="@+id/tv_text"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <ImageView 
         android:id="@+id/iv_image"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/tv_text"/>
    </RelativeLayout>
  2. 在src中新建一个类
    所继承的类与上一步layout的根view相同

    public class CustomView extends RelativeLayout{
    
    //layout中包含的view
    private View mRootView;
    private TextView mTextView;
    private ImageView mImageView;
    
    //重载一参构造方法
    public CustomView(Context context) {
        this(context,null);
    }
    
    //重载两参构造方法
    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mRootView=LayoutInflater.from(context).inflate(R.layout.layout_view, this,true);
        mTextView=(TextView) mRootView.findViewById(R.id.tv_text);
        mImageView=(ImageView) mRootView.findViewById(R.id.iv_image);
    }
    
    //自定义方法
    public void setText(String text){
        mTextView.setText(text);
    }
    
    //自定义方法
    public void setImageResource(int resId){
        mImageView.setImageResource(resId);
    }
    }
  3. 现在可以把它当做普通控件使用了。

发布了69 篇原创文章 · 获赞 55 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/xmh19936688/article/details/51481940