android控件layout函数,Android自定义view之继承RelativeLayout的控件

第一步:

在values下新建attrs.xml文件,在此文件中将一些想要设置的属性写入

//二者都使用到相同的可以提取出来

//本例子只用此view来做演示

//

//

//

//

//

//

第二步

新建一个layout_view.xml,在此布局中添加你要自定义的ui样式,这里只添加一张图片+一句话

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#000000">

android:id="@+id/iv"

android:layout_width="15dp"

android:layout_height="15dp"

android:src="@drawable/customer_service" />

android:id="@+id/tv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textColor="#ffffff"

android:textSize="16sp" />

第三步

创建一个DamoRelayoutView 继承RelativeLayout,在这个类里面做一些关联操作

public class DamoRelayoutView extends RelativeLayout{

@BindView(R.id.tv)

TextView tv;

@BindView(R.id.iv)

ImageView iv;

public DamoRelayoutView (Context context){

super(context);

init(context,null);

}

public DamoRelayoutView (Context context,AttributeSet attrs){

super(context,attrs);

init(context,attrs);

}

public DamoRelayoutView (Context context,AttributeSet attrs,int defStyleAttr){

super(context,attrs,defStyleAttr);

init(context,attrs);

}

private void init(Context context,AttributeSet attrs){

inflate(context,R.layout.layout_view,this);

ButterKnife.bind(this);

TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.damoView);

//关联icon

int leftIconId = ta.getResourceId(R.styleable.damoView_dIcon, R.drawable.customer_service);

iv.setImageDrawable(getResources().getDrawable(leftIconId,null));

//关联textcolor

int textColor = ta.getColor(R.styleable.damoView_textColor, Color.parseColor("#94e9ff"));

tv.setTextColor(textColor);

//关联textsize

float textSize = ta.getDimension(R.styleable.damoView_textSize, getResources().getDimension(R.dimen.default_textsize));

tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,textSize);

//关联text

String text = ta.getString(R.styleable.damoView_text);

if (text != null){

tv.setText(text);

}

ta.recycle();

}

//只设置了文本,如果想设置颜色,大小,只需向此函数一样暴露出去即可

public void setText(String text){

tv.setText(text);

}

public CharSequence getText(){

return tv.getText();

}

}

第四步

将写好的自定义控件动态添加到MainActivity.java类中

layout_main.xml中就是一个简单的LinearLayout,这里不在赘述

public class MainActivity {

@BindView(R.id.ll)

LinearLayout ll;

@Override

protected void onCreate(Bundle savesInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.layout_main};

ButterKnife.bind(this);

addView();

}

private void addView(){

DamoRelayoutView view = new DamoRelayoutView (MainActivity.this);

view.setText("我是damo");

ll.addView(view);

}

}

以上四步就可以完成一个简单的自定义控件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值