美文网首页
Android自定义控件相关使用

Android自定义控件相关使用

作者: 简单Liml | 来源:发表于2017-05-15 10:05 被阅读12次

用代码简单介绍下自定义控件的使用:

先看主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

布局文件来自于xml文件 test_lin.xml:

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical" >

android:id="@+id/btn"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="haha1111"/>

android:id="@+id/btn2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="haha2222"/>

主布局文件activity_main.xml如下:

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" >

android:layout_width="match_parent"

android:layout_height="wrap_content"

test:customtextSize="100dp"

test:customtextStr="123啦啦啦"/>

注意这边的命名空间。

相关文章

网友评论

      本文标题:Android自定义控件相关使用

      本文链接:https://www.haomeiwen.com/subject/ffocxxtx.html