底部标签页实现思路
现在的APP,大多在页面底部显示标签栏Tabbar,用于切换不同栏目的页面。Tabbar起源于iOS,iOS的Tabbar自动位于页面下方,可是Android搬过来的时候做了改动,自带的Tabbar位于页面上方,很不适合用户的使用习惯。为此我们在Android实现底部标签栏,得额外进行底部适配处理,适配思路基本都是在底部罗列一排的按钮,然后根据点击不同的按钮,跳到不同的Activity页面。具体的实现方式,博主目前发现了三个:
1、使用TabActivity。其中在布局文件中设置TabHost、TabWidget和RadioButton,在代码文件中应用TabActivity、TabSpec和CompoundButton。2、使用ActivityGroup。将几个栏目的首页Activity都放入ActivityGroup,然后根据点击事件选择切换到哪个Activity。
3、使用FragmentActivity和Fragment。将几个栏目的首页Fragment都放入FragmentActivity,可自动响应点击事件。
其中TabActivity继承自ActivityGroup,目前Android声称TabActivity与ActivityGroup都已废弃,建议采用Fragment和FragmentManager来代替。从实现代码来看,TabActivity和ActivityGroup两种方式的代码量都较多,而FragmentActivity方式的代码就显得很简洁,所以博主也推荐第三种方式。
下面简要介绍三种方式的代码实现:
TabActivity方式
调用代码如下:import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TabHost;
@SuppressWarnings("deprecation")
public class TestTabActivity extends TabActivity implements OnCheckedChangeListener {
private static final String TAG = "TestTabActivity";
private Bundle mBundle = new Bundle();
private TabHost tab_host;
private CompoundButton first_button;
private CompoundButton second_button;
private CompoundButton third_button;
private String FIRST_TAG = "first";
private String SECOND_TAG = "second";
private String THIRD_TAG = "third";
private TabHost.TabSpec getNewTab(String spec, int label, int icon, Intent intent) {
return tab_host
.newTabSpec(spec)
.setIndicator(getString(label), getResources().getDrawable(icon))
.setContent(intent);
}
private void setButtonCheck(CompoundButton button) {
if (button.equals(first_button)) {
button.setChecked(true);
second_button.setChecked(false);
third_button.setChecked(false);
} else if (button.equals(third_button)) {
button.setChecked(true);
second_button.setChecked(false);
first_button.setChecked(false);
} else if (button.equals(second_button)) {
button.setChecked(true);
first_button.setChecked(false);
third_button.setChecked(false);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);