按照本教程,我在应用程序的操作栏中创建了一些选项卡。 https://www.youtube.com/watch?v=gMu8XhxUBl8 此应用程序只需在用户单击选项卡时更改布局。 虽然没有编译错误,但我无法运行我的程序。它显示了消息,不幸停止了程序。但我在这里找不到错误。亲爱的。
这是我使用的代码,
public class TabsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab TabA = bar.newTab().setText("Tab A");
ActionBar.Tab TabB = bar.newTab().setText("Tab B");
ActionBar.Tab TabC = bar.newTab().setText("Tab C");
Log.d("action bar", "action bar");
Fragment fragmentA = new AFragmentTab();
Fragment fragmentB = new BFragmentTab();
Fragment fragmentC = new CFragmentTab();
Log.d("Fragments", "Fragments created");
TabA.setTabListener(new MyTabsListener(fragmentA));
TabB.setTabListener(new MyTabsListener(fragmentB));
TabC.setTabListener(new MyTabsListener(fragmentC));
Log.d("Tab listner", "Tab listner created");
bar.addTab(TabA);
bar.addTab(TabB);
bar.addTab(TabC);
Log.d("tabs added", "tabs added");
}
protected class MyTabsListener implements ActionBar.TabListener {
private android.app.Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
Log.d("my tab listner", "my tab listner");
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Log.d("tab released", "tab released");
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragment_container, fragment, null);
Log.d("ta selected", "tab selected");
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// some people needed this line as well to make it work:
ft.remove(fragment);
Log.d("tab unselected", "tab unselected");
}
}
每个片段java文件编码都是这样的,
public class AFragmentTab extends android.app.Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_a, container, false);
}
main.xml文件,
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/fragment_container"></LinearLayout>
</LinearLayout>