android自定义控件相关使用

用代码简单介绍下自定义控件的使用:
先看主activity:
public class customImView extends LinearLayout{
public customImView(Context context, AttributeSet attrs) {
super(context, attrs);

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.customView);
String text = a.getString(R.styleable.customView_customtextStr);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.test_lin, this, true);
Button btn = (Button)view.findViewById(R.id.btn2);
btn.setText(text);
}
}

里面的样式styleable 来自于attrs.xml
<resources>
<declare-styleable name="customView">
<attr name="customtextSize" format="dimension"/>
<attr name="customtextStr" format="string"/>
</declare-styleable>
</resources>

布局文件来自于xml文件 test_lin.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="haha1111"/>
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="haha2222"/>
</LinearLayout>

主布局文件activity_main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:test="http://schemas.android.com/apk/res/com.lml.customview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<com.lml.customview.view.customImView
android:layout_width="match_parent"
android:layout_height="wrap_content"
test:customtextSize="100dp"
test:customtextStr="123啦啦啦"/>

</RelativeLayout>

注意这边的命名空间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值