在很多情况下,我们需要自定义属于自己的layout,毕竟很多时候我们需要把
一些经常用到的布局保存下来,在以后继续使用,避免重复代码。
标题栏实例
xml代码如下
style="?android:attr/borderlessButtonStyle"//去掉Button的边框
<?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="50dp"
android:background="@color/colorBackground"
>
<Button
android:layout_width="42dp"
android:layout_height="42dp"
android:id="@+id/title_btn"
android:layout_margin="5dp"
style="?android:attr/borderlessButtonStyle"
android:background="@drawable/back"
></Button>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="标题栏"
android:layout_gravity="center|top"
android:layout_weight="1"
android:textColor="@android:color/black"
android:gravity="center"
></TextView>
<Button
android:layout_height="42dp"
android:layout_width="42dp"
android:layout_margin="5dp"
android:background="@drawable/edit"
style="?android:attr/borderlessButtonStyle"
></Button>
</LinearLayout>
使用的方法,在需要使用的layout里加上
<include layout="@layout/title"></include>
注意将自带的标题栏隐藏掉
1.在MainActivity中使用代码
ActionBar actionBar=getSupportActionBar();
if(actionBar!=null)
{
actionBar.hide();
}
2.在style里面修改
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">这一句代码
自定义控件
很多情况下,对于我们刚才使用的布局中,我们的两个按钮肯定会响应
事件,那么我们最后自定义一个控件来使用,并且把响应控件包装在这个控件
里面。
新建java文件继承自LinerLayout
代码如下
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attres)
{
super(context,attres);
//第一个参数是id,第二个参数是父布局
LayoutInflater.from(context).inflate(R.layout.title,this);
Button button1=(Button)findViewById(R.id.title_btn);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
}
}
调用代码如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<!--<include layout="@layout/title"></include>-->
<com.example.uicustomview.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
></com.example.uicustomview.TitleLayout>
</LinearLayout>
总结:
- 对于很多控件,我们都可以自定义布局来实现控件
- 最后实现了自定义控件后也应该实现自定义的控件