我正在使用默認的Swipe Tab Fragment代碼,Android啓動時啓動一個新的Android應用程序。我已經想出瞭如何修改我的數據並使用選項卡,但我還沒有想出如何添加一個簡單的片段到已有的。我想在選項卡的頂部或正下方添加一個信息欄。我相信這很簡單,我只是不知道怎麼大聲笑。我通過實例學習。如何將一個片段添加到ViewPager? addView崩潰我的應用程序
我試着添加viewpager視圖,但我的應用程序崩潰了,我相信我完全做錯了。
在我的MainActivity: ...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
SubBarFragment infobar = new SubBarFragment();
mViewPager.addView(infobar.getView());
.....[extra code for menus and things]
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
....[code to show specific tabs and return the tab's fragment]
infobarfragment.java
public class InfobarFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.infobar, container, false);
return view;
}
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
infobar.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="horizontal" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_wifi" />
<TextView
android:id="@+id/statusText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Wifi Status Information" />
</LinearLayout>
你有一個適配器的ViewPager,使用方法getItem/instanciateItem(取決於你使用的是:碎片還是簡單的視圖)。這些方法爲viewpager對象提供了所有需要的視圖。 – Andreas 2013-04-26 08:47:30
你可以在適配器中返回多個片段嗎?我已經想到如何使用Santhosh的幫助來添加片段,但它只是將它視爲我可以滑過的另一個「頁面」。無論我在哪個網頁,我都希望它持久。我曾希望它在標籤上方,但我認爲這不可能。因此,現在我猜,讓它下面的標籤是好的。思考? – CREW 2013-04-26 11:15:47