Android自定义控件有两种,一种是组合。比如一个linearlayout 里面有textview,imageview.
这样的好处是,写一个就可以多处使用。- view_image_and_button.xml 你的组合控件的布局文件
2.自定义属性
app\src\main\res\values\attrs.xml
注释:
参考:- reference:参考某一资源ID。 示例:
- color:颜色值。
- boolean:布尔值。
示例: [java] 复制代码 代码如下:
- dimension:尺寸值。
示例: [java] 复制代码 代码如下:
- float:浮点值。
示例: [java] 复制代码 代码如下:
- integer:整型值。
示例: [java] 复制代码 代码如下:
- string:字符串。
示例: [java] 复制代码 代码如下:
- fraction:百分数。
示例: [java] 复制代码 代码如下:
- enum:枚举值。
示例: [java] 复制代码 代码如下:
- flag:位或运算。
示例: [java] 复制代码 代码如下:
11.多类型。
示例: [java] 复制代码 代码如下:
3.代码
import android.content.Context;import android.content.res.TypedArray;import android.util.AttributeSet;import android.view.LayoutInflater;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import com.chinaCEB.cebActivity.R;/** * Created by Administrator on 2016/6/22. */public class ImageAndButton extends LinearLayout { private ImageView imageView; private TextView textView; public ImageAndButton(Context context) { super(context); } public ImageAndButton(Context context, AttributeSet attrs) { super(context, attrs); LinearLayout linearLayout= (LinearLayout) LayoutInflater.from(context).inflate(R.layout.view_image_and_button,this,true); imageView = (ImageView) linearLayout.findViewById(R.id.img_top); textView = (TextView) linearLayout.findViewById(R.id.tv_bottom); TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.ImageBtnWithText); textView.setText(typedArray.getText(R.styleable.ImageBtnWithText_text)); imageView.setImageResource(typedArray.getResourceId(R.styleable.ImageBtnWithText_src,R.mipmap.exit)); } public ImageAndButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setImageView(int resourseId){ imageView.setImageResource(resourseId); } public void setTextView(String string){ textView.setText(string); }}
4.使用:
注意:要加上下面这句: xmlns:xinyu=”http://schemas.android.com/apk/res-auto”