Android在点击转到viewpager中的第一个片段后返回到相同的片段

时间:2014-04-23 06:20:34

标签: android android-viewpager fragment

我开发了一个应用程序,我使用视图分页器使用fragment.In我使用片段class移动到另一个页面。在第二个片段类我有一个按钮回来我写代码直接移动到第一个片段通过fragment.replace但是在替换第一个片段之后我不会将寻呼机页面滚动到一个到另一个意味着当我点击后退按钮时我移动到第一个片段但我无法返回到该类别。所以我不知道再次移动/滚动页面去第一个到第二个片段。请提前帮助我,谢谢。

My First class follewing:

enter code here
         public class ViewPagerMainActivity extends FragmentActivity implements
    OnClickListener, OnPageChangeListener {

   // all variable declare here
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



    getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    );

    setTheme(android.R.style.Theme_Light_NoTitleBar);


    setContentView(R.layout.view_pager_main);
    // other code here

}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(
            android.support.v4.app.FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int pos) {
        switch (pos) {

        case 0:
            return FirstFragment.newInstance("");

        case 1:
            return SecondFragment.newInstance("");

        default:
            return SecondFragment.newInstance("Default");
        }
    }

    @Override
    public int getCount() {
        return 2; // return no of fragment created by us
    }
}

@Override
public void onClick(View v) {

}

@Override
public void onPageScrollStateChanged(int arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
    // TODO Auto-generated method stub

}

@Override
public void onPageSelected(int arg0) {
    // TODO Auto-generated method stub

}
@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
}

}

enter code here  SECOND FILE
           public class FirstFragment extends Fragment implements OnTouchListener {

      // all variable decalre here
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    getActivity().setTheme(android.R.style.Theme_Light_NoTitleBar);
    v = inflater.inflate(R.layout.sliding_lock_pager, container, false);

    // other code here
    return v;
}

public static FirstFragment newInstance(String text) {

    FirstFragment f = new FirstFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);
    f.setArguments(b);

    return f;
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    return false;
}

}      第三档     在此处输入代码           公共类SecondFragment扩展Fragment实现OnClickListener {

// all varible decalare here
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    getActivity().setTheme(android.R.style.Theme_Light_NoTitleBar);
    View v = inflater.inflate(R.layout.password, container, false);

    // other code here
    // this method move to main pager 
    txtBack.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            final android.support.v4.app.FragmentTransaction ft = getFragmentManager()
                    .beginTransaction();

                ft.replace(R.id.layputMainPager, new FirstFragment(),
                        "NewFragmentTag");
                ft.addToBackStack(null);
                ft.commit();
        }
    });

    return v;
}

public static SecondFragment newInstance(String text) {

    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);
    f.setArguments(b);
    return f;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

}

}

   See in secondFragment class when i back through back button then i want to scroll again to that page i not do that. i move again to that page though page scroll. and in ft.replace(R.id.layputMainPager, new FirstFragment()) R.id.layputMainPager is  `class ViewPagerMainActivity` class xml files a

主要布局ID。

2 个答案:

答案 0 :(得分:3)

几天前我遇到了同样的问题,我认为你正在混合两种不同的实现:

  1. 如果您正在使用ViewPager片段。您可以使用ViewPager的setCurrentItem()方法移动到next或prev片段。

  2. 如果你只使用片段然后在片段之间移动你可以使用FragmentTransaction类方法,如replace(),add()等。

  3. 希望这会清除事情。如果仍然不清楚,请分享代码。

    修改

    你可以重载onBackPressed()方法,例如:

    @Override
    public void onBackPressed() {
        // you can also check for current viewpager item by 
        // mViewpager.getCurrentItem()  
         mViewPager.setCurrentItem(precFragment, true);
    
    }
    

    如果您在片段中添加了按钮,则可以执行以下操作:

    Button back =  (Button) rootView.findViewById(R.id.back_button);
    back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((YourActivity)getActivity()).mViewPager.setCurrentItem(prevFragment);
    
            }
        });
    

    编辑:添加代码

      public class MainActivity extends Activity {
    
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
     * derivative, which will keep every loaded fragment in memory. If this
     * becomes too memory intensive, it may be best to switch to a
     * {@link android.support.v13.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;
    
    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
    
        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public void onBackPressed() {
    
         mViewPager.setCurrentItem(0, true);
    
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
    
        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public Fragment getItem(int position) {
            switch (position) {
            case 0:
                return new FirstFragment();
            case 1:
                return new SecondFragment();
            default:
                break;
            }
            return null;
        }
    
        @Override
        public int getCount() {
            return 2;
        }
    
        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            }
            return null;
        }
    }
    
     }
    

    FirstFragment文件

      public class FirstFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    
    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static FirstFragment newInstance(int sectionNumber) {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }
    
    public FirstFragment() {
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_first, container,
                false);
        Button next =  (Button) rootView.findViewById(R.id.button1);
        next.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                ((MainActivity)getActivity()).mViewPager.setCurrentItem(1);
    
            }
        });
        return rootView;
    }
    }
    

    SecondFragment文件

     public class SecondFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    
    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static SecondFragment newInstance(int sectionNumber) {
        SecondFragment fragment = new SecondFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }
    
    public SecondFragment() {
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.second_fragment, container,
                false);
    
        Button back =  (Button) rootView.findViewById(R.id.button1);
        back.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                ((MainActivity)getActivity()).mViewPager.setCurrentItem(0);
    
            }
        });
        return rootView;
    }
     }
    

    请参阅SecondFragment文件中的onBackPressed()方法和back.setOnClickListener()。 希望这会有所帮助

答案 1 :(得分:0)

接口有更好的实现。

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_first, container, false);
    Button next = (Button) rootView.findViewById(R.id.button1);
    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ((MainActivity) getActivity()).mViewPager.setCurrentItem(1);

        }
    });
    return rootView;
}

应该替换为: 片段文件

public class FirstFragment extends Fragment {

private static final String ARG_SECTION_NUMBER = "section_number";

private OnSetCurrentItemListener mListener;
private int mSection;

public interface OnSetCurrentItemListener {
    void onGotoItem(int position);
}


public static FirstFragment newInstance(int sectionNumber) {
    FirstFragment fragment = new FirstFragment();
    Bundle args = new Bundle();

    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
}


// This method pass a listener to the activity through Fragment LifeCycle creation.
// No needs to cast you Activity cause the method bring it; 
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnSetCurrentItemListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " needs to implement OnSetCurrentItemListener");
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getArguments();
    mSection = extras.getInt(ARG_SECTION_NUMBER);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_first, container, false);
    Button next = (Button) rootView.findViewById(R.id.button1);
    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int target = mSection + 1;
            target = (target < 0) ? 0 : target; //checks bounds
            //to go next
            mListener.onGotoItem(mSection + 1);
            //to prev
            //mListener.onGotoItem(mSection - 1);
        }
    });
    return rootView;
}
}

关于你的活动文件:

public class ViewPagerMainActivity extends FragmentActivity implements OnSetCurrentItemListener {

...

@Override
public void onGotoItem(int position) {
    mViewPager.setCurrentItem(position);

}