在开发Android应用中,有时候会在多个界面中出现同样的布局

如在顶部或底部显示菜单栏,时间显示等。为了避免麻烦,不用

在每个界面都布局,这个时候我们用到了BaseActivity(不是系统

的自己定义的)在BaseActivity布局里,我们可以把公用的布局先

写出来,如界面顶部有返回按钮,有当前界面Title。在界面底部有

时间显示栏,且时间和系统时间同步,不断刷新。在BaseActivity

的布局里,我们留出LinearLayout这样一个线性布局,并且设置属性

id,这样其他界面的layout放置到这个LinearLayout里就可以了。

我们看一下具体的使用步骤:

1、定义一个公用类的Activity我这里叫MyBaseActivity继承Activity

并且该MyBaseActivity为抽象类abstract,因为里面有抽象方法

2、定义一个基本类如FirstActivity继承MyBaseActivity并实现

MyBaseActivity里面的抽象方法

3、在MyBaseActivity类中有两个抽象方法onBaseCreare(Bundle bundle)

和initView()其中 onBaseCreare()方法顾名思义是实现界面显示的也就

是类似于onCreate()中的setContentView(layout),initView()方法用于

初始化一些数据,如Title的设置,时间显示等。

4、在MyBaseActivity类中有getbtn_left()方法,可获取公共控件的控制。


贴出详细代码:

先看xml布局:

//activity_my_base.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:weightSum="10" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:weightSum="3" >
        <Button
            android:id="@+id/button1_base"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="左按钮" />
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="标题" />
        <Button
            android:id="@+id/button3_base"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="右按钮" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/layout_id"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="8.5"
        android:orientation="horizontal" >
    </LinearLayout>
    <LinearLayout
        android:id="@+id/layout_bottom"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.5" >
        <TextView
            android:id="@+id/time"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:gravity="center"
            android:text="标题" />
    </LinearLayout>
</LinearLayout>


//activity_first.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:weightSum="1"
    tools:context=".FirstActivity" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:orientation="vertical" >
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="into SecondActivity" />
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:text="Button2" />
    </LinearLayout>
</LinearLayout>


//activity_second.xml

<LinearLayout 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" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:weightSum="3" >
        <Button
            android:id="@+id/button1_second"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="返    回" />
        
        <Button
            android:id="@+id/button12_second"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="Button" />
        
        <Button
            android:id="@+id/button3_second"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button" />
    </LinearLayout>
</LinearLayout>


//接下来看一下类中的源码

首先是公共类 MyBaseActivity 

package com.example.testbaseactivity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public abstract class MyBaseActivity extends Activity implements OnClickListener{
// 内容区域的布局
private View contentView;
private LinearLayout layoutBody;
private Button btn1;
private Button btn2;
private TextView tv;
private TextView vTime;
private String timeString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_base);
btn1 = (Button) findViewById(R.id.button1_base);
btn2 = (Button) findViewById(R.id.button3_base);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
tv = (TextView) findViewById(R.id.title);
layoutBody = (LinearLayout) findViewById(R.id.layout_id);
vTime = (TextView) findViewById(R.id.time);
onBaseCreare(savedInstanceState);
initView();
}
/**
 * 初始化界面
 * @param bundle
 */
public abstract void onBaseCreare(Bundle bundle);
/**
 * 初始化数据
 */
public abstract void initView();
/**
 * 底部栏刷新时间
 * 刷新间隔1s
 */
public void setTime() {
int delay = 0;
int period = 1000;// 循环间隔 1000ms
java.util.Timer timer = new java.util.Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
timeString = getTime();
myhandler.sendEmptyMessage(0x0001);
}
}, delay, period);
}
@SuppressLint("HandlerLeak")
private Handler myhandler = new Handler() {
public void dispatchMessage(android.os.Message msg) {
switch (msg.what) {
case 0x0001:
vTime.setText(timeString);
break;
}
}
};
@SuppressLint("SimpleDateFormat")
public static String getTime() {
Date nowdate = new Date(); // 当前时间
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(nowdate);
}
/**
 * 设置标题
 * 
 * @param title
 */
public void setTitle(String title) {
if (null != tv) {
tv.setText(title);
}
}
/**
 * 隐藏上方的标题栏
 */
public void hideTitleView() {
if (null != btn1) {
btn1.setVisibility(View.INVISIBLE);
}
}
public void setContentViewId(int layoutId) {
contentView = getLayoutInflater().inflate(layoutId, null);
if (layoutBody.getChildCount() > 0) {
layoutBody.removeAllViews();
}
if (contentView != null) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, 
LayoutParams.MATCH_PARENT);
layoutBody.addView(contentView, params);
}
}
/**
 * 得到左边的按钮
 * 
 * @return
 */
public Button getbtn_left() {
return btn1;
}
/**
 * 得到右边的按钮
 * 
 * @return
 */
public Button getbtn_right() {
return btn2;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0.equals(btn1)){
Toast.makeText(MyBaseActivity.this, "MyBaseActivity---btn1", 
Toast.LENGTH_SHORT).show();
}
if(arg0.equals(btn2)){
Toast.makeText(MyBaseActivity.this, "MyBaseActivity---btn2", 
Toast.LENGTH_SHORT).show();
}
}
}

//第一个界面 FirstActivity 

package com.example.testbaseactivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class FirstActivity extends MyBaseActivity {
private Button btn1;
private Button btn2;
private Button btn_left;
private Button btn_right;
@Override
public void onBaseCreare(Bundle bundle) {
setContentViewId(R.layout.activity_first);
btn_left = getbtn_left();
btn_right = getbtn_right();
findViewById();
}
@Override
public void initView() {
setTitle("FirstActivity");
setTime();
}
public void findViewById(){
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
if(arg0.equals(btn1)){
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
if(arg0.equals(btn2)){
Toast.makeText(FirstActivity.this, "FirstActivity---btn2", 
Toast.LENGTH_SHORT).show();
}
if(arg0.equals(btn_left)){
Toast.makeText(FirstActivity.this, "FirstActivity---btn_left", 
Toast.LENGTH_SHORT).show();
}
if(arg0.equals(btn_right)){
Toast.makeText(FirstActivity.this, "FirstActivity---btn_right", 
Toast.LENGTH_SHORT).show();
}
}
}


//第二个界面

package com.example.testbaseactivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SecondActivity extends MyBaseActivity implements OnClickListener{
private Button btn;
@Override
public void onBaseCreare(Bundle bundle) {
setContentViewId(R.layout.activity_second);
btn = (Button) findViewById(R.id.button1_second);
btn.setOnClickListener(this);
}
@Override
public void initView() {
setTime();
setTitle("SecondActivity");
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0.equals(btn)){
finish();
}
}
}


//manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testbaseactivity"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="16" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testbaseactivity.FirstActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.testbaseactivity.MyBaseActivity" >
        </activity>
        <activity
            android:name="com.example.testbaseactivity.SecondActivity"  >
        </activity>
    </application>
</manifest>
给出效果图

wKiom1VUNqKCLq8SAABioVoSwMk964.jpg           wKiom1VUNqKRHvddAAByt6Qy-_Q391.jpg

wKioL1VUOBzwJfF5AAG6B2SopPo957.jpg