我正在尝试使用导航选项卡在某些片段之间进行更改,就像您可以使用 Tabhost 一样。
不幸的是,选项卡显示在 ActionBar 中,但片段的内容却没有。这是我的 MainActivity 代码:
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends SherlockFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = bar
.newTab()
.setText("Tab1")
.setTabListener(new MyTabListener(this, new Fragment1()));
bar.addTab(tab);
tab = bar
.newTab()
.setText("Tab2")
.setTabListener(new MyTabListener(this, new Fragment2()));
bar.addTab(tab);
}
public static class MyTabListener implements TabListener {
private MainActivity mActivity;
private Fragment mFragment;
public MyTabListener(MainActivity activity, Fragment fragment) {
mActivity = activity;
mFragment = fragment;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ignoredFt) {
FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.content, mFragment, null);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
片段1.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
}
片段1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
主.xml:
<?xml version="1.0" encoding="utf-8"?>
<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_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/content" >
</LinearLayout>
</LinearLayout>
Fragment2 的结构与 Fragment1 相同,但 TextView 中的其他文本!
所以似乎片段的视图无法显示在 main.xml 的内容中。
我希望你能帮帮我...