Android 自定义TitleBar

1. 去掉Android自带TitleBar

在styles.xml中新建 style

<style name="notitle" parent="android:Theme">

    <item name="android:windowNoTitle">true</item>

</style>


在AndroidManifest.xml中相应的Activity标签中使用该style

<activity

    android:name=".MainActivity"

    android:theme="@style/notitle"

>


2. 编写TitleBar 布局xml文件 my_title.xml

<com.coco.view.MyTitleBar

xmlns:android:=http://shemes.android.com/apk/res/android"

android:id="@+id/my_title"

android:layout_width="match_parent"

android:layout_height="50dp"

android:background="#ffffff"

android:orientation="horizontal">

<LinearLayout

android:layout_width="50dp"

android:layout_height="match_parent"

android:id="@+id/mytitle_left"

android:orientation="vertical"

android:gravity="center"

android:layout_alignParentLeft="true"/>




<LinearLayout

android:layout_width="50dp"

android:layout_height="match_parent"

android:id="@+id/mytitle_center"

android:orientation="vertical"

android:gravity="center"

android:layout_toRightOf="@id/mytitle_left"/>



<LinearLayout

android:layout_width="50dp"

android:layout_height="match_parent"

android:id="@+id/mytitle_right"

android:orientation="vertical"

android:gravity="center"

android:layout_alignParentRight="true"/>



</com.coco.view.MyTitleBar>


3. 编写MyTitleBar 类 继承RelativeLayout

并在onFinishInflate方法中给各view赋值


public class MyTitleBar extends RelativeLayout{

LinearLayout leftView;

LinearLayout centerView;

LinearLayout rightView;



public MyTitleBar(Context context){

super(context);

}



protected void onFinishInflate(){

super.onFinishInflate();

leftView = (LinearLayout) findViewById(R.id.mytitle_left);

centerView = (LinearLayout) findViewById(R.id.mytitle_center);

rightView = (LinearLayout) findViewById(R.id.mytitle_right);

}



public void addLeftView(View view){

if(leftView != null){

leftView.addView(view);

}

}






public void addCenterView(View view){

if(lcenterView != null){

centerView.addView(view);

}

}






public void addRightView(View view){

if(rightView != null){

rightView.addView(view);

}

}

}

}


4. 在activity_main.xml布局文件中include my_title.xml


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


5. 在MainActivity中使用该TitleBar


MyTitleBar myTitleBar;

protected void onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    myTitleBar = (myTitleBar) findViewById(R.id.my_title);

    TextView tv = new TextView(this);

    tv.setText("Hello Left view");

    myTitleBar.addLeftView(tv);

}









你可能感兴趣的:(Android 自定义TitleBar)