`
l540151663
  • 浏览: 180876 次
  • 性别: Icon_minigender_1
  • 来自: 浙江
社区版块
存档分类
最新评论

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>

注意这边的命名空间。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics