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

来源:互联网 发布:java 健身房管理系统 编辑:程序博客网 时间:2024/05/17 22:01

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

  • Android自助餐之自定义控件一从layout自定义控件
      • 查看全套目录
    • 从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中包含的viewprivate 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. 现在可以把它当做普通控件使用了。

0 0
原创粉丝点击