创建自定义控件

1.在layout目录下创建title.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!-- 自建伪标题ActionBar -->
 3 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 4                 android:layout_width="match_parent"
 5                 android:layout_height="50dp"
 6                 android:background="@android:color/holo_green_dark">
 7 
 8     <ImageView
 9         android:id="@+id/img_title"
10         android:layout_width="50dp"
11         android:layout_height="50dp"
12         android:layout_marginLeft="7dp"
13         android:scaleType="fitXY"
14         android:src="@drawable/ic_launcher"/>
15 
16     <TextView
17         android:id="@+id/tv_title"
18         android:layout_width="wrap_content"
19         android:layout_height="50dp"
20         android:layout_marginLeft="5dp"
21         android:layout_marginTop="15dp"
22         android:layout_toRightOf="@id/img_title"
23         android:text="@string/title_tv"/>
24 
25     <Button
26         android:id="@+id/btn_title"
27         android:layout_width="60dp"
28         android:layout_height="50dp"
29         android:layout_alignParentRight="true"
30         android:layout_marginRight="7dp"
31         android:text="@string/title_settings"/>
32 
33 
34 </RelativeLayout>

2.新建ownui包创建titleView.java:

 1 /**
 2  * 创建自定义控件
 3  */
 4 public class TitleLayout extends Layout
 5 {
 6 
 7     public TitleLayout(Context context, AttributeSet attrs)
 8     {
 9         super(context, attrs);
10         LayoutInflater.from(context).inflate(R.layout.title, this);//TODO 填充xml
11 
12         Button btnTitle = (Button) findViewById(R.id.btn_title);
13 
14         if(getContext() instanceof MainActivity)//判断一个对象是否是指定类型的实例对象
15         {
16             btnTitle.setText(R.string.title_settings);
17         }
18     }
19 }

 

posted on 2015-11-29 14:26  starFarming  阅读(147)  评论(0编辑  收藏  举报