从API级别11引入了操作栏。在本文中,我将说明如何在带有片段的操作栏中创建标签。 最终结果显示在下面,用户可以在两个选项卡之间移动。
创建操作栏和选项卡
第一步是获取操作栏引用并将标签添加到其中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i=1; i <= 3; i++) {
Tab tab = bar.newTab();
tab.setText("Tab " + i);
tab.setTabListener(this);
bar.addTab(tab);
}
}
请注意,首先我们不使用任何“主”布局。 其次,在第3行,我们只需使用getActionBar方法即可获得对操作栏的引用。 在第4行中,我们设置了导航模式
NAVIGATION_MODE_TABS 。 支持三种不同的导航类型:
- 导航模式列表
- 导航模式标准
- 导航模式选项卡
完成这些步骤后,我们必须创建选项卡并将其添加到操作栏中。 在我们的示例中,我们创建了三个不同的选项卡。 我们想要的是,当用户触摸其中一个选项卡时,UI内容会更改。 为此,我们需要两件事:
- 用户根据选定的选项卡更改选项卡时填充UI的片段
- 当用户与选项卡交互时获取通知的侦听器
标签片段
在我们的示例中,片段将非常简单,它仅在屏幕中间显示一个文本。 布局看起来像:
<?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="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
虽然片段源代码非常简单:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getArguments();
index = data.getInt("idx");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, null);
TextView tv = (TextView) v.findViewById(R.id.msg);
tv.setText("Fragment " + (index + 1));
return v;
}
请注意,我们使用参数bundle(第2,3行)传递了片段索引,现在我们有了片段,我们只需要实现侦听器即可。
标签监听器
我们可以使Activity实现监听器,以便在用户选择选项卡时显示相对片段。
public class MainActivity extends Activity implements TabListener {
...
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Fragment f = null;
TabFragment tf = null;
if (fragList.size() > tab.getPosition())
fragList.get(tab.getPosition());
if (f == null) {
tf = new TabFragment();
Bundle data = new Bundle();
data.putInt("idx", tab.getPosition());
tf.setArguments(data);
fragList.add(tf);
}
else
tf = (TabFragment) f;
ft.replace(android.R.id.content, tf);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragList.size() > tab.getPosition()) {
ft.remove(fragList.get(tab.getPosition()));
}
}
}
TabListener有几个我们必须重写的方法。 最重要的是onTabSelected ,当用户选择一个选项卡时将调用它。 在此方法中,首先检查片段列表中是否有片段(第9-10行),如果是,我们将对其进行重用并显示该片段(请参阅第20行)。 如果没有,我们创建片段行(12-18)并将其添加到片段列表中。 最后(第22行),我们仅用正确的片段替换了UI内容( android.R.id.content )。 结果如下所示:
![]() | ![]() |
翻译自: https://www.javacodegeeks.com/2013/06/android-action-bar-with-tab.html