【发布时间】:2013-04-26 17:30:56
【问题描述】:
我正在使用默认的 Swipe Tab Fragment 代码,当您启动新的 Android 应用程序时,Android 会使用该代码启动。我已经想出了如何修改我的数据和使用选项卡,但我还没有想出如何将一个简单的片段添加到已经存在的内容中。我想在选项卡的顶部或正下方添加一个信息栏。我敢肯定这很简单,我只是不知道如何大声笑。我通过例子来学习。
我尝试向 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" />
信息栏.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 对象提供了所有需要的视图。
-
您可以在适配器中返回多个片段吗?我已经想出了如何使用 Santhosh 的帮助添加片段,但它只是将其视为另一个我可以浏览的“页面”。无论我在哪个页面上,我都希望它是持久的。我曾希望它位于标签上方,但我认为这是不可能的。所以现在我想把它放在标签下面是好的。想法?
标签: android layout android-fragments android-viewpager