自定义控件类

在自定义标题栏时,自定义的标题栏总会置于系统自带的标题栏之下,于是在activity_main.xml中发现了这样一部分内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

 

1
<include layout="@layout/content_main" /> //此为引入布局的方法

末尾一句引入content_main布局,而content_main.xml中也只引入了自定义的titlebar.xml标题栏布局,因此<include layout="@layout/content_main" />之上的内容即为系统自带的标题栏布局,删掉即可。接着在MainActivity中删除看起来是绑定标题栏一类的东西

1
2
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

 

标题栏就出现了
自定义titlebar自定义titlebar
///////////////////////////////////////////////////////////////
设置自定义控件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//自定义控件类
public class TitleLayout extends LinearLayout implements View.OnClickListener{
//在布局中引入该控件会调用该构造函数
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);//前者为加载指定布局,后者为指定布局添加一个父布局,即为TitleLayout这个布局
Button btn_back = (Button) findViewById(R.id.back);
Button btn_edit = (Button) findViewById(R.id.edit);
btn_back.setOnClickListener(this);
btn_edit.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back:
((Activity) getContext()).finish();//这句话要注意
case R.id.edit:
Toast.makeText(getContext(),"you edit?",Toast.LENGTH_SHORT).show();
}

}
}

 

需要注意的是,既然是写一个控件类出来,所加载的布局文件R.layout.title就相当于和该类捆绑了起来,在不同的活动中使用该控件亦是创建了不同的对象。也因此,只需要注重第一次编写该类时的逻辑关系即可

posted @ 2016-03-20 22:00  Gabyler  阅读(225)  评论(0编辑  收藏  举报