您的位置:首页 > 移动开发 > Android开发

我的android_code_lib:自定义标题栏

2014-09-02 17:07 302 查看
==android自带的标题略有点难看,写代码写累了。自己总结下吧。

其实也不算完全的原创,这是看过guolin大大的blog之后才想得到的。

首先,建立一个xml文件,作为标题栏的布局文件。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#A4D3EE" >

<!-- 左侧按钮,具体参数可以自己设定 -->
<Button
android:id="@+id/bt_left"
android:layout_width="60sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_margin="5sp"
android:text="left"
android:textColor="#fff"
android:textSize="15sp" />

<!-- 中间的标题文本 -->
<TextView
android:id="@+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="5sp"
android:text="title"
android:textColor="#fff"
android:textSize="30sp" />

<!-- 右侧按钮 -->
<Button
android:id="@+id/bt_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="5sp"
android:text="right"
android:textColor="#fff"
android:textSize="15sp" />

</RelativeLayout>

再建立一个java文件,继承自FrameLayout。
public class TitleBar extends FrameLayout{

private Button btLeft, btRight;
private TextView titleText;
public TitleBar(Context context, AttributeSet attrs) {
super(context, attrs);
//动态载入标题栏的xml文件
LayoutInflater.from(context).inflate(R.layout.title_bar, this);
//获取标题栏的左侧按钮,右侧按钮,以及中间的标题文本
titleText = (TextView)findViewById(R.id.titleText);
btLeft = (Button) findViewById(R.id.bt_left);
btRight = (Button) findViewById(R.id.bt_right);
}
// 设置标题文字
public void setTitleText(String text) {
this.titleText.setText(text);
}
// 设置左按钮文字
public void setBtLeftText(String text) {
this.btLeft.setText(text);
}
// 设置右按钮文字
public void setBtRightText(String text) {
this.btRight.setText(text);
}
// 设置左侧按钮的监听事件
public void setBtLeftListener(OnClickListener l){
this.btLeft.setOnClickListener(l);
}
// 设置右侧按钮的监听事件
public void setBtRightListener(OnClickListener l){
this.btRight.setOnClickListener(l);
}

// 隐藏左侧按钮
public void hideLeftButton(){
btLeft.setVisibility(8);
}
// 隐藏右侧按钮
public void hideRightButton(){
btRight.setVisibility(8);
}
}

接着在activity的布局文件中,(一般是最顶部拉),放入标题栏
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#A4D3EE" >

这里要写的是TitleBar类的包名和类名,其余操作与普通的控件无异
<packageName.TitleBar
android:id="@+id/title_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>

在Activity中,和找到普通控件的方法一样,用findViewById方法找到该控件:
接下来就可以进行一系列的操作了,比如设置标题栏的文字等等。

TitleBar titleBar;
titleBar = (TitleBar)findViewById(R.id.title_bar);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: