【问题标题】:Android : handle fragments in a ViewPager with buttonAndroid:使用按钮处理 ViewPager 中的片段
【发布时间】:2012-11-20 02:59:14
【问题描述】:

我的活动中有 3 个片段,由扩展 FragmentPagerAdapter 的自定义类管理。

我的主要 xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
      >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
          />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
          />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
          />


  <android.support.v4.view.ViewPager
                android:id="@+id/tabviewpager"
                android:layout_width="fill_parent"
                android:layout_height="0dp"
                android:layout_weight="1" />

</LinearLayout>

我的活动:

public class RankingFragmentActivity extends FragmentActivity{
....

  List fragments = new Vector();


fragments.add(Fragment.instantiate(this,Tab1Fragment.class.getName()));
fragments.add(Fragment.instantiate(this,Tab2Fragment.class.getName()));
fragments.add(Fragment.instantiate(this,Tab3Fragment.class.getName()));

//adapter
MyPagerAdapter mPagerAdapter =  new MyPagerAdapter(super.getSupportFragmentManager(), fragments);

ViewPager pager = (ViewPager) super.findViewById(R.id.tabviewpager);

pager.setAdapter(this.mPagerAdapter);

}

我可以完美地从片段从 letf 切换到右(以及从右到左)。

我想将按钮设置为侦听器(以更改显示的片段),但我不知道该怎么做。

例如: 点击 button1 :显示片段 1

点击button2:显示片段2

点击button3:显示片段3

谢谢!

【问题讨论】:

    标签: android fragment android-fragmentactivity


    【解决方案1】:

    答案就在the documentation for FragmentPagerAdapter

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.goto_first);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mPager.setCurrentItem(0);
            }
        });
    

    【讨论】:

    • 完美~感谢您的帮助和链接!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多