Android引入标题栏

title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/title"
>

<Button
android:id="@+id/b1"
android:textColor="#fff"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上一页"/>
<TextView
android:textColor="#fff"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="真香小说"/>
<Button
android:layout_gravity="center"
android:id="@+id/b2"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一页"/>
</LinearLayout>

main.xml中引入开头

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<include layout="@layout/title"/>

</LinearLayout>

在main.java中隐藏原来的标题栏

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar=getSupportActionBar();
if(actionBar!=null){
actionBar.hide();
}
}


 目前只是将标题页的demo导入到了main界面中,但是如果想要给button添加点击事件的话,我们还需要在main中去写点击事件,
有于标题栏很多时候会在很多界面使用而且标题栏的工能一般是不会发生改变的,我们所以我们可以吧点击事件也写在一个模板里面
首先新建TitleLayout .java继承LinearLayout 类重写其中的构造函数,引入TitleLayout 时会调用这个构造函数,然后使用
LayoutInflater.from(context).inflate(R.layout.title,this);
方法该方法第一个参数是要加载布局文件的id第二个是
添加一个父布局,然后再其中写点击事件
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attributeSet){
super(context,attributeSet);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button b1=(Button)findViewById(R.id.b1);
Button b2=(Button)findViewById(R.id.b2);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
((Activity)getContext()).finish();
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(),"下一页",Toast.LENGTH_LONG).show();
}
});
}


}
至此自定义事件已经制作完成,然后开始导入在main.xml中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.uicustonviews.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>


posted @ 2019-01-23 14:59  王怀宇  阅读(209)  评论(0编辑  收藏  举报