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

布局文件来自于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啦啦啦"/>

注意这边的命名空间。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容