android 快速开发(三)巧用公共标题栏 (1),android 开发从入门到精通
public OnClickListener getBackOnClickLisener() {
return null;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
代码简洁,并且有设置标题栏文字、标题栏以为的布局和随心所欲的返回事件
这些都归功于 CommonActivity:
package com.yqy.yqy_commontitlebar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
public abstract class CommonActivity extends FragmentActivity {
private TextView leftTv, centerTv, rightTv;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.common_title_bar);
leftTv = (TextView) findViewById(R.id.leftTv);
centerTv = (TextView) findViewById(R.id.centerTv);
rightTv = (TextView) findViewById(R.id.rightTv);
if (getBackOnClickLisener() == null) {
leftTv.setOnClickListener(new BackOnClickLisener());
} else {
leftTv.setOnClickListener(getBackOnClickLisener());
}
init();
}
/**
设置标题和主布局
@author yqy
@date 2016-1-7 下午 3:44:55
@param title
@param layoutId
*/
public void setTitleAndContentLayoutId(String title, int layoutId) {
getLayoutInflater().inflate(layoutId,
(ViewGroup) centerTv.getParent().getParent());
centerTv.setText(title);
}
public abstract void init();
public abstract OnClickListener getBackOnClickLisener();
class BackOnClickLisener implements OnClickListener {
@Override
public void onClick(View arg0) {
finish();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
leftTv.performClick();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
OnCreare 方法初始化标题栏布局和点击事件
setTitleAndContentLayoutId(String title, int layoutId)用来设置标题栏的标题文字和主要布局
有两个方法前面带有 pub
lic abstract 修饰符目的是让子类复写这些 ?父类调用
标题栏布局贴上:
评论