把ViewPager 从一个fragment切换到另一个fragment中

Viewpager 中有两个pages,在每一个 fragment中,我放入一个按钮到switching fragment中,但是如果我改变方向,switching不能运行。对于switching fragment,我使用的是 OnChangePageButtonClick 接口。为什么会出现这种情况呢?
ViewPager Activity:

public class ViewPagerMusic extends FragmentActivity implements OnChangePageButtonClick {
    private ViewPager vp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_pager_music);
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(super.getSupportFragmentManager(), fragments);

        vp = (ViewPager)findViewById(R.id.viewpager);
        vp.setAdapter(viewPagerAdapter);
    }
    private class ViewPagerAdapter extends FragmentStatePagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                MainPage mainPage = new MainPage();
                mainPage.setOnChengeButtonListener(ViewPagerMusic.this);
                return mainPage;
            case 1:
                PlaylistPage playlistPage = new PlaylistPage();
                playlistPage.setOnChengeButtonListener(ViewPagerMusic.this);
                return playlistPage;
        }
        return null;
    }
       @Override
        public int getCount() {
            return 2;
        }
    }
    @Override
    public void selectPage(int page) {
        vp.setCurrentItem(page);        
    }
}

Frgamnets:

public class MainPage extends Fragment {
    public MainPage() {
        setRetainInstance(true);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.music_main_page, container, false);
        ImageButton btnPlaylist = (ImageButton)v.findViewById(R.id.btnGoPlaylist2);
        btnPlaylist.setOnClickListener(onButtonListener);
        return v;
    }
    private OnClickListener onButtonListener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            onChangePageButtonClick.selectPage(1);
        }
    };
    public void setOnBackButtonListener(OnChangePageButtonClick onChangePageButtonClick) {
        this.onChangePageButtonClick = onChangePageButtonClick;
    }
    private OnChangePageButtonClick onChangePageButtonClick;
}

Playlist fragment 与 MainPage fragment相似。

8个回答

没明白你那switching 的意思,是不能切换fragment ?有没有可能是你的代码有问题? OnChangePageButtonClick 设置那一设置错了item index ?

亲 问题 没说明白啊
到底想问什么呢

有没有可能是你的代码有问题? OnChangePageButtonClick 设置那一设置错了item index ?

public class ViewPagerCompat extends ViewPager {

//mViewTouchMode表示ViewPager是否全权控制滑动事件,默认为false,即不控制
private boolean mViewTouchMode = false;

public ViewPagerCompat(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void setViewTouchMode(boolean b) {
    if (b && !isFakeDragging()) {
        //全权控制滑动事件
        beginFakeDrag();
    } else if (!b && isFakeDragging()) {
        //终止控制滑动事件
        endFakeDrag();
    }
    mViewTouchMode = b;
}

/**
 * 在mViewTouchMode为true的时候,ViewPager不拦截点击事件,点击事件将由子View处理
 */
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    if (mViewTouchMode) {
        return false;
    }
    return super.onInterceptTouchEvent(event);
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    try {
        return super.onTouchEvent(ev);
    } catch (Exception e) {
        return false;
    }
}

/**
 * 在mViewTouchMode为true或者滑动方向不是左右的时候,ViewPager将放弃控制点击事件,
 * 这样做有利于在ViewPager中加入ListView等可以滑动的控件,否则两者之间的滑动将会有冲突
 */
@Override
public boolean arrowScroll(int direction) {
    if (mViewTouchMode) return false;
    if (direction != FOCUS_LEFT && direction != FOCUS_RIGHT) return false;
    return super.arrowScroll(direction);
}

}

如果是数据消失了。你就去看一下fragment的生命周期。生命周期很多问题。翻两页,前一页的数据就会重新赋值。

请参考这个类,解决fragMent的图activity之间的问题
public class FragmentViewpageAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener{
private List fragments; // 每个Fragment对应一个Page
private FragmentManager fragmentManager;
private ViewPager viewPager; // viewPager对象
private int currentPageIndex = 0; // 当前page索引(切换之前)

private OnExtraPageChangeListener onExtraPageChangeListener; // ViewPager切换页面时的额外功能添加接口

public FragmentViewpageAdapter(FragmentManager fragmentManager, ViewPager viewPager , List<Fragment> fragments) {
    this.fragments = fragments;
    this.fragmentManager = fragmentManager;
    this.viewPager = viewPager;
    this.viewPager.setAdapter(this);
    this.viewPager.setOnPageChangeListener(this);
}

@Override
public int getCount() {
    return fragments.size();
}

@Override
public boolean isViewFromObject(View view, Object o) {
    return view == o;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView(fragments.get(position).getView()); // 移出viewpager两边之外的page布局
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = fragments.get(position);
    if(!fragment.isAdded()){ // 如果fragment还没有added
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.add(fragment, fragment.getClass().getSimpleName());
        ft.commit();
        /**
         * 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
         * 会在进程的主线程中,用异步的方式来执行。
         * 如果想要立即执行这个等待中的操作,就要调用这个方法(只能在主线程中调用)。
         * 要注意的是,所有的回调和相关的行为都会在这个调用中被执行完成,因此要仔细确认这个方法的调用位置。
         */
        fragmentManager.executePendingTransactions();
    }

    if(fragment.getView().getParent() == null){
        container.addView(fragment.getView()); // 为viewpager增加布局
    }

    return fragment.getView();
}

/**
 * 当前page索引(切换之前)
 * @return
 */
public int getCurrentPageIndex() {
    return currentPageIndex;
}

public OnExtraPageChangeListener getOnExtraPageChangeListener() {
    return onExtraPageChangeListener;
}

/**
 * 设置页面切换额外功能监听器
 * @param onExtraPageChangeListener
 */
public void setOnExtraPageChangeListener(OnExtraPageChangeListener onExtraPageChangeListener) {
    this.onExtraPageChangeListener = onExtraPageChangeListener;
}

@Override
public void onPageScrolled(int i, float v, int i2) {
    if(null != onExtraPageChangeListener){ // 如果设置了额外功能接口
        onExtraPageChangeListener.onExtraPageScrolled(i, v, i2);
    }
}

@Override
public void onPageSelected(int i) {
    fragments.get(currentPageIndex).onPause(); // 调用切换前Fargment的onPause()

// fragments.get(currentPageIndex).onStop(); // 调用切换前Fargment的onStop()
if(fragments.get(i).isAdded()){
// fragments.get(i).onStart(); // 调用切换后Fargment的onStart()
fragments.get(i).onResume(); // 调用切换后Fargment的onResume()
}
currentPageIndex = i;

    if(null != onExtraPageChangeListener){ // 如果设置了额外功能接口
        onExtraPageChangeListener.onExtraPageSelected(i);
    }

}

@Override
public void onPageScrollStateChanged(int i) {
    if(null != onExtraPageChangeListener){ // 如果设置了额外功能接口
        onExtraPageChangeListener.onExtraPageScrollStateChanged(i);
    }
}


/**
 * page切换额外功能接口
 */
static class OnExtraPageChangeListener{
    public void onExtraPageScrolled(int i, float v, int i2){}
    public void onExtraPageSelected(int i){}
    public void onExtraPageScrollStateChanged(int i){}
}

}

private int currentPageIndex = 0; // 当前page索引(切换之前)

http://download.csdn.net/detail/u013372185/8075709 你可以看看这个链接,这个项目里面也是用的ViewPager,但是我项目中切换view用的是ViewFlipper。。。不过和ViewPager差不多,

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
从fragment启动另一个fragment
一、Fragment.show(); private static final String DIALOG_PHONE_NUMBERS ="phone_numbers" ;//fragment的标识符PhoneNumbersFragment.newInstance(nums).show(getActivity().getSupportFragmentManager(),DIALOG_PHON
Fragment交互,接口方式从一个Fragment传参到另一个Fragment
在要传参的Fragment里面定义一个接口,接口里面有个方法,然后再activity里面实现接口的方法,先看效果图: package com.example.myandroid.Fragment.Interaction1; import android.app.Activity; import android.app.Fragment; import android.os.Bund
如何在fragment中点击按钮切换到另一个fragment中?
一共有4个fragment,分别是contact(联系人),friends(朋友),search(查找),more(更多)。使用的都是同一个布局,每个fragment中都有四个内部按钮,可以切换到其他的3个fragment中。rn现在只考虑在contact中,实现点4个(其实有效的是3个),切换到其他3个fragment中。rnrn现在的情况是,点击contactfragment中的按钮,toast会响应,但是fragment不会跳转。这是怎么回事,下面是两个类的代码。rnrn这是contactfragment。rn[code=java]rnpublic class ContactFragment extends Fragment implements OnClickListener rn MainActivity activity = (MainActivity) getActivity();rn View view = null;rn Button btn_inner_contact;rn Button btn_inner_friends;rn Button btn_inner_search;rn Button btn_inner_more;rnrn @Overridern public View onCreateView(LayoutInflater inflater, ViewGroup container,rn Bundle savedInstanceState) rn view = inflater.inflate(R.layout.frag_content, container, false);rn TextView textview_hint = (TextView) viewrn .findViewById(R.id.textview_hint);rn textview_hint.setText("Contact");rn initComponent();rn return view;rn rnrn private void initComponent() rn btn_inner_contact = (Button) viewrn .findViewById(R.id.button_inner_contact);rn btn_inner_friends = (Button) viewrn .findViewById(R.id.button_inner_friends);rn btn_inner_search = (Button) view.findViewById(R.id.button_inner_search);rn btn_inner_more = (Button) view.findViewById(R.id.button_inner_more);rnrn btn_inner_contact.setOnClickListener(this);rn btn_inner_friends.setOnClickListener(this);rn btn_inner_search.setOnClickListener(this);rn btn_inner_more.setOnClickListener(this);rn rnrn @Overridern public void onClick(View v) rnrn FragmentManager fm = activity.getFragmentManager();rn FragmentTransaction ft = fm.beginTransaction();rn switch (v.getId()) rn case R.id.button_inner_contact:rn Toast.makeText(getActivity(), "点击了内部contact按钮", Toast.LENGTH_SHORT)rn .show();rn if (activity.contactFragment == null) rn activity.contactFragment = new ContactFragment();rn rn ft.replace(R.id.framelayout_content, activity.contactFragment);rnrn break;rn case R.id.button_inner_friends:rn Toast.makeText(getActivity(), "点击了内部friends按钮", Toast.LENGTH_SHORT)rn if (activity.friendsFragment == null) rn activity.friendsFragment = new FriendsFragment();rn rn ft.replace(R.id.framelayout_content, activity.friendsFragment);rn break;rn case R.id.button_inner_more:rn if (activity.moreFragment == null) rn activity.moreFragment = new MoreFragment();rn rn ft.replace(R.id.framelayout_content, activity.moreFragment);rn break;rn case R.id.button_inner_search:rn if (activity.searchFragment == null) rn activity.searchFragment = new SearchFragment();rn rn ft.replace(R.id.framelayout_content, activity.searchFragment);rn break;rn default:rn break;rnrn rn ft.commit();rn rnrnrnrn[/code]rnrn这是mainactivity类,mainactivity中的那四个按钮及其响应时间是fragment外部的四个按钮,与内部的inner按钮没关系。rn[code=java]rnpublic class MainActivity extends Activity implements OnClickListener rn public ContactFragment contactFragment;rn public FriendsFragment friendsFragment;rn public MoreFragment moreFragment;rn public SearchFragment searchFragment;rn private Button btn_contact;rn private Button btn_friends;rn private Button btn_search;rn private Button btn_more;rnrn @Overridern protected void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.activity_main);rn initcomponet();rn initview();rnrn rnrn private void initview() rn contactFragment = new ContactFragment();rn FragmentManager fm = getFragmentManager();rn FragmentTransaction ft = fm.beginTransaction();rn ft.add(R.id.framelayout_content, contactFragment);rn ft.commit();rn rnrn private void initcomponet() rnrn btn_contact = (Button) findViewById(R.id.button_contact);rn btn_friends = (Button) findViewById(R.id.button_friends);rn btn_more = (Button) findViewById(R.id.button_more);rn btn_search = (Button) findViewById(R.id.button_search);rn btn_contact.setOnClickListener(this);rn btn_friends.setOnClickListener(this);rn btn_more.setOnClickListener(this);rn btn_search.setOnClickListener(this);rn rnrn @Overridern public void onClick(View v) rn FragmentManager fm = getFragmentManager();rn FragmentTransaction ft = fm.beginTransaction();rn switch (v.getId()) rn case R.id.button_contact:rn if (contactFragment == null) rn contactFragment = new ContactFragment();rn rn ft.replace(R.id.framelayout_content, contactFragment);rnrn break;rn case R.id.button_friends:rn if (friendsFragment == null) rn friendsFragment = new FriendsFragment();rn rn ft.replace(R.id.framelayout_content, friendsFragment);rnrn break;rn case R.id.button_more:rn if (moreFragment == null) rn moreFragment = new MoreFragment();rn rn ft.replace(R.id.framelayout_content, moreFragment);rnrn break;rn case R.id.button_search:rn if (searchFragment == null) rn searchFragment = new SearchFragment();rn rn ft.replace(R.id.framelayout_content, searchFragment);rn break;rnrn default:rn break;rn rn ft.commit();rn rnrnrn[/code]
如何在fragment中点击导航栏一项切换到另一个fragment中 ?
[img=https://img-bbs.csdn.net/upload/201604/02/1459595442_795699.png][/img]
ViewPager和Fragment
ViewPager和Fragment的嵌套使用
ViewPager和fragment
ViewPager和fragment结合使用,病使用Callbacks功能
ViewPager fragment
使用ViewPager,fragment实现侧滑导航的效果
Fragment + ViewPager
Fragment + ViewPager 一个小代码项目,组成了一个可以滑动的界面,代码中含有注释.如果需要,可以下载下来看一下,当个参考
ViewPager 和 Fragment
ViewPager 和 Fragment的交叉使用,产生滑动切换View android
fragment viewpager
外面fragment 可以点击 里面fragment viewpager 可滑动 可点击 配详解! 希望大家能分享给我一个 让内外fragment 都可以滑动的Demo
Fragment和ViewPager
Fragment和ViewPager实现侧滑
viewpager fragment
viewPager的简单实用以及如何删除当前的fragment
Fragment和Viewpager
Fragment和ViewPager的使用
ViewPager与Fragment
使用ViewPager加载Fragment
RecycleView + Fragment 替换 ViewPager + Fragment
RecycleView + Fragment 替换 ViewPager + Fragment 的Demo,效果还不错
fragment嵌套viewPager中放fragment
fragment嵌套viewPager,viewpager中也是fragment切换。
fragment跳转到其他的fragment。在viewpager中
首先在fragment的依赖Activity中加:public interface Fragment2Fragment{ public void gotoFragment(MyViewPager viewPager); } private Fragment2Fragment fragment2Fragment; public void setFragment2Fragment(Fragm...
安卓在一个活动(Activity)里加载碎片(Fragment)并切换到另一个碎片(Fragment)
我在开发的时候遇到了这个问题,就是如何在Activity加载一个Fragment并通过点击Fragment里面的Button切换到其他Fragment,当时我也找了很多资料但感觉不怎么实用最后想了很久终于想到一个方法解决这个问题:也就是通过使用异步(handler)来实现,我们首先在加载Fragment的Activity中写 实现切换部分: public Handler handler =ne
Fragment中嵌套Viewpager
Fragment中嵌套Viewpager
Viewpager中的fragment内嵌fragment,滑动报错
02-07 16:26:30.621: E/AndroidRuntime(19951): java.lang.NullPointerExceptionn02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.Fragment.instantiate(Fragment.java:399)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.FragmentState.instantiate(Fragment.java:97)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1790)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.Fragment.performCreate(Fragment.java:1489)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:893)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.view.ViewPager.populate(ViewPager.java:1128)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.view.ViewPager.populate(ViewPager.java:975)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1505)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.View.measure(View.java:15575)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.View.measure(View.java:15575)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5107)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.View.measure(View.java:15575)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5107)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.View.measure(View.java:15575)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5107)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)n02-07 16:26:30.621: E/AndroidRuntime(19951): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2423)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.View.measure(View.java:15575)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2033)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1251)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1427)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1144)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4730)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.Choreographer.doCallbacks(Choreographer.java:555)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.Choreographer.doFrame(Choreographer.java:525)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.os.Handler.handleCallback(Handler.java:615)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.os.Handler.dispatchMessage(Handler.java:92)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.os.Looper.loop(Looper.java:137)n02-07 16:26:30.621: E/AndroidRuntime(19951): at android.app.ActivityThread.main(ActivityThread.java:4947)n02-07 16:26:30.621: E/AndroidRuntime(19951): at java.lang.reflect.Method.invokeNative(Native Method)n02-07 16:26:30.621: E/AndroidRuntime(19951): at java.lang.reflect.Method.invoke(Method.java:511)n02-07 16:26:30.621: E/AndroidRuntime(19951): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)n02-07 16:26:30.621: E/AndroidRuntime(19951): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)n02-07 16:26:30.621: E/AndroidRuntime(19951): at dalvik.system.NativeStart.main(Native Method)
ViewPager + Fragment + viewPager
目前遇到一个问题;就是viewpager搭配fragment; 然后fragment中使用viewpager做轮播广告;其中 fragment1 和fragment2 中都使用了同一个封装的viewpager轮播广告控件(数据是放在控件中请求的); 有时会遇到fragment1数据请求下来并展示成功,然后fragment2 请求发出去了, 我断点发现没有回调onSuccess方法; 有时fragment2成功,fragment1失败; 有时又好使,都能成功;下面帖代码rn@Overridern protected void onAttachedToWindow() rn super.onAttachedToWindow();rn list=new ArrayList<>();rn if(url != null)rn EzNodeManager.getNodesInfo(null, url, 0, new Callback>() rn @Overridern public void success(List ezDrupalNodes, Response response) rn list.clear();rn if(ezDrupalNodes!=null&&ezDrupalNodes.size()>0)rn for(int i=0;i
动态更新ViewPager中的Fragment
http://stackoverflow.com/questions/7263291/viewpager-pageradapter-not-updating-the-view/8024557#8024557 There are several ways to achieve this. The first option is easier, but bit more ineffic
Fragment在ViewPager中的生命周期
Fragment在ViewPager中的生命周期
viewpager中fragment的生命周期管理
最近在一个项目中,使用到了多个Fragment加载到ViewPager,每个Fragment是通过同一个Adapter加载数据,而根据代码的设计,每一个Fragment中的数据都会通过Adapter中Right和Left类发送; @Override public void right(int current, int id, int position) {//向右点击按钮 Log.i("
ViewPager中Fragment的生命周期
切换ViewPager时Fragment的生命周期变化这里有一个MainActivity,MainActivity中有一个ViewPager,使用的适配器是FragmentPagerAdapter,ViewPager中有三个Fragment:FirstFragment,SecondFragment,ThirdFragment。刚进入MainActivity,Log是这样的:可以看到,MainActi
判断当前Fragment是否切换到前台
我们都知道,Activity有onResume()方法,可以很方便程序员在该Activity(重新)展示在用户面前的时候,执行一些数据更新的操作,例如需要重新加载网络数据。那么Fragment呢,查看Fragment源码,可以知道,类似的方法是:// Hint provided by the app that this fragment is currently visible to the use
Viewpager里添加Fragment,Fragment里面添加一个Viewpager
在Viewpager里添加了3个Fragment,在第一个Fragment中再添加一个Viewpager进行广告图片轮询,但是问题就来的,当切换到第三个fragment的时候,第一个Fragment里Viewpager的图片看不见了,但是其他数据还完好无缺,锁屏再解锁图片又回来了,这是什么情况???求大神!!!
从一个Activity切换到另一个Activity
采用Android5.x进行讲解。本课程包含了几乎所有的Android开发技术,例如,Eclipse和Android Studio开发环境的搭建、各种控件的详细使用方法、布局、四大应用程序组件、数据存储、网络、对话框、Toast、通知、Intent、Android5.x新特性、Fragment、ActionBar、拖放技术、组件开发、硬件访问、定时器、Android NDK等技术。
fragment里面嵌套另一个fragment
最近换了工作,说白了,就是去填坑啦,首页改版,原来是viewpager+标签切换滑动实现,现在改成popupwindow+recyclerview实现,为了减少工时,我在原来的基础上复用了fragment,即需要实现在一个fragment里面嵌入另一个fragment。FragmentTransaction ft = getChildFragmentManager().beginTransacti...
fragment跳转另一个fragment的问题!
项目地址:rn链接: https://pan.baidu.com/s/1OHSva0M5PIQMWNP0iwzlLg 提取码: csf5 rnrn求大能帮我解决一下。我不知道怎么去写这个跳转。rnrn![图片说明](https://img-ask.csdn.net/upload/201903/12/1552331749_241936.png)rnrnrnrn鼠标点击需要跳转(例如点击“苹果手机”);rnrnrn```rnpublic class MsgFragment extends Fragment rnrn View view;rn TextView textView;rn private int i;rn private String str;rnrnrn private String[] mVals = new String[] "苹果手机", "笔记本电脑", "电饭煲", "腊肉",rn "特产", "剃须刀", "宝宝", "康佳" ;rn private LayoutInflater mInflater;rn private FlowLayout mFlowLayout;rnrn //自定义recyclerveiw的适配器rnrnrnrn @Overridern public void onCreate(@Nullable Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rnrn mInflater = LayoutInflater.from(getContext());rnrnrn rnrn public MsgFragment() rn rnrnrn @Overridern public View onCreateView(LayoutInflater inflater, ViewGroup container,rn Bundle savedInstanceState) rnrn view = inflater.inflate(R.layout.fragment_msg, container, false);rnrn mFlowLayout = view.findViewById(R.id.id_flowlayout);rnrnrn initData();rnrnrn return view;rn rn public void initData() rn /**rn * 找到搜索标签的控件rn */rn for ( i = 0; i < mVals.length; i++) rn final TextView tv = (TextView) mInflater.inflate(rn R.layout.search_label_tv, mFlowLayout, false);rn tv.setText(mVals[i]);rn str = tv.getText().toString();rn //点击事件rn tv.setOnClickListener(new View.OnClickListener() rn @Overridern public void onClick(View v) rn try rnrn switch (str) rn case "苹果手机":rnrn rn break;rn case "笔记本电脑":rnrn break;rn case "电饭煲":rnrn break;rn case "腊肉":rnrn break;rn case "特产":rnrn break;rn case "剃须刀":rnrn break;rn case "宝宝":rnrn break;rn case "康佳":rnrn break;rn default:rnrn break;rn rnrnrnrnrnrn catch (Exception e) rn e.printStackTrace();rn rnrn rn );rn mFlowLayout.addView(tv);//添加到父Viewrn rnrnrn rnrnrnrn```rn需要跳转到的fragmentrnrn```rnpublic class CollectFragment extends Fragment rn private View view;//定义view用来设置fragment的layoutrn public RecyclerView mCollectRecyclerView;//定义RecyclerViewrn //定义以goodsentity实体类为对象的数据集合rn private ArrayList goodsEntityList = new ArrayList();rn //自定义recyclerveiw的适配器rn private CollectRecycleAdapter mCollectRecyclerAdapter;rnrn @Nullablern @Overridern public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) rn //获取fragment的layoutrn view = inflater.inflate(R.layout.item_content, container, false);rn //对recycleview进行配置rn initRecyclerView();rn //模拟数据rn initData();rn return view;rn rnrn /**rn * TODO 模拟数据rn */rn private void initData() rn for (int i=0;i<10;i++)rn GoodsEntity goodsEntity=new GoodsEntity();rn goodsEntity.setGoodsName("模拟数据"+i);rn goodsEntity.setGoodsPrice("100"+i);rn goodsEntityList.add(goodsEntity);rn rn rnrn /**rn * TODO 对recycleview进行配置rn */rnrn private void initRecyclerView() rn //获取RecyclerViewrn mCollectRecyclerView=view.findViewById(R.id.collect_recyclerView);rn //创建adapterrn mCollectRecyclerAdapter = new CollectRecycleAdapter(getActivity(), goodsEntityList);rn //给RecyclerView设置adapterrn mCollectRecyclerView.setAdapter(mCollectRecyclerAdapter);rn //设置layoutManager,可以设置显示效果,是线性布局、grid布局,还是瀑布流布局rn //参数是:上下文、列表方向(横向还是纵向)、是否倒叙rn mCollectRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));rn //设置item的分割线rn mCollectRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));rn //RecyclerView中没有item的监听事件,需要自己在适配器中写一个监听事件的接口。参数根据自定义rn mCollectRecyclerAdapter.setOnItemClickListener(new CollectRecycleAdapter.OnItemClickListener() rn @Overridern public void OnItemClick(View view, GoodsEntity data) rn //此处进行监听事件的业务处理rn Toast.makeText(getActivity(),"我是item",Toast.LENGTH_SHORT).show();rn rn );rn rnrnrnrn```
解决viewpager中一个fragment嵌套fragment出现重叠现象
当viewpager第一个或者第二个Fragment嵌套了几个Fragment时候,用的是addFragment、show、hide方法时候,当view pager切换到后面的时候会出现界面重叠现象,如图 我的解决方法之一是在内部的fragment背景设置不透明可可以。 解放方法之二是在viewpager第二个Fragment的onDestoryView()方法里面remove掉内部的
在一个Fragment中获取另一个Fragment中的值(FindFragmentByTag方法)
-
一个Fragment中的listview 更新另一个fragment中的 listview
最近写一小程序,遇到点小问题rn界面是由多个Fragment组成,现在想完成的工作是:rnrn点击Fragment1中的ListView1,想将其值传输到另一个Fragment2中的ListView2rn试了很久都不行rnrn网上有基于继承 BaseAdapter 的自动更新,但这种方法 getview() 中生成的数据都一样rn导致点击传过去的数据会覆盖全部rnrn[img=https://img-bbs.csdn.net/upload/201307/23/1374572301_924015.jpg][/img]rn[img=https://img-bbs.csdn.net/upload/201307/23/1374572314_820344.jpg][/img]rnrn比如在“运行”中点击第三项,那“运行”中的所有项目都变成第三个项目的内容rnrn不知道有没有高手做过类似项目,有什么好的解决办法呢?
Fragment中嵌套ViewPager,ViewPager中包含多个Fragment的时候,第一个Fragment一直不显示
在Fragment中嵌套ViewPager,然后ViewPager中呈现Fragment的时候, 页面一直空白,可能的原因就是在初始化Adapter的时候使用了getFragmentManager,getFragmentManager到的是activity对所包含fragment的Manager,而如果是fragment嵌套fragment,那么就需要利用getChildFragmentManag...
viewpager和fragment实现预加载和fragment的单一加载
1. viewpager的预加载       setOffscreenPageLimit(commentAdapter.getCount() - 1):通过此api可以实现viewpager的预加载,默认为1,加载两个 2. fragment的单一加载:详见文章Fragment的setUserVisibleHint方法实现懒加载,总结的挺好,就不班门弄斧了
Fragment 在ViewPager中的资源释放时机
第一次加载ViewPager时,会加载第一个和第二个选项卡。即Fragment调用了onCreate-&amp;gt;onResume();但是在选中第三个选项卡时,第一个选项卡的Fragment会调用onPause() onStop(),如果此时又回到第二个选项卡,那么第一个选项卡会调用onResume(),就是说只要当前选项卡在目标选项卡附近,它就会开始重新加载了。但是这些都不会调用onDestroy...
fragment在viewpager中listview的数据加载
viewpageer中,fragment有个listview。通过按钮跳转到另一个设置界面,在设置界面点完成按钮,把设置界面的一个textview传回fragment里,并显示在listview中,该怎么做,求大神指点,fragment是取的单独的xml,不是放在某个activity里面,本人菜鸟一个,跪求指点迷津
Fragment中加载ViewPager报错
我在fragment中的顶端设置了自动滚动的viewpager,跟手机网页新浪的那种自动滚动条类似,我在MainActivity中使用这段代码完全正常,但是加载到fragment中就会出错,自动滑动的效果有,也没问题,问题就在我拖动,滑到下一条的时候会报以下错误,好像是子view重复加载了父view控件,但是一直没弄明白是那个地方重复加载了,有知道的大神求帮忙解答一下原因……rnrn[img=https://img-bbs.csdn.net/upload/201411/27/1417059068_58797.jpg][/img]rnrnpublic class FragmentMerchantOfDetail extends Fragment rn rn private View view;rn rn private ViewPager viewPager;rn rn //viewpager图片资源IDrn private final int[] viewPagerImageId = R.drawable.viewpager1,R.drawable.viewpager2,R.drawable.image2;rn rn private ArrayList imageList;rn rn //上一个页面的位置rn protected int lastPosition;rn rn //viewpager的PointGroup rn private LinearLayout pointGroup;rn rn private boolean isRunning = false;//是否自动滚动rn rn @Overridern public View onCreateView(LayoutInflater inflater, ViewGroup container,rn Bundle savedInstanceState) rn rn view = inflater.inflate(R.layout.merchant_detail, container, false);rn initViewPager();rn rn return view;rn rn rn private void initViewPager() rn //viewpager视图的初始化代码rn viewPager = (ViewPager) view.findViewById(R.id.view_pager);rn pointGroup = (LinearLayout) view.findViewById(R.id.point_group);rn imageList = new ArrayList();rn rn for (int i = 0; i < viewPagerImageId.length; i++) rn //viewpager的图片资源rn ImageView imagePhoto = new ImageView(getActivity());rn imagePhoto.setBackgroundResource(viewPagerImageId[i]);rn imageList.add(imagePhoto);rn rn //point指示点 的参数即相关的设置rn ImageView imagePoint = new ImageView(getActivity());rn LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);rn params.rightMargin = 20;rn params.bottomMargin = 20;rn rn imagePoint.setLayoutParams(params);rn imagePoint.setBackgroundResource(R.drawable.normal_point);rn pointGroup.addView(imagePoint);rn rn rn viewPager.setAdapter(new MyPagerAdapter());rn rn viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() rn rn @Overridern //页面切换后调用rn public void onPageSelected(int position) rn position = position % imageList.size();rn pointGroup.getChildAt(position).setBackgroundResource(R.drawable.focuesed_point);rn pointGroup.getChildAt(lastPosition).setBackgroundResource(R.drawable.normal_point);rn lastPosition = position;rn rn rn @Overridern /**rn * 页面正在滑动的时候,回调rn */rn public void onPageScrolled(int arg0, float arg1, int arg2) rn rn @Overridern /**rn * 当页面状态发生变化的时候,回调rn */rn public void onPageScrollStateChanged(int arg0) rn rn );rn rn isRunning = true;rn handler.sendEmptyMessageDelayed(0, 2000);rn rn rn private Handler handler = new Handler()rnrn @Overridern public void handleMessage(Message msg) rn //让viewpager滑动到下一页rn viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);rn rn if (isRunning) rn //每个2秒发送一次消息,实现自动滑动的效果rn handler.sendEmptyMessageDelayed(0, 2000);rn rn rn rn ;rn rn @Overridern public void onDestroy() rn isRunning = false;rn super.onDestroy();rn rnrn private class MyPagerAdapter extends PagerAdapterrn rn @Overridern public int getCount() rn return Integer.MAX_VALUE;rn rnrn @Overridern public Object instantiateItem(ViewGroup container, int position) rn container.addView(imageList.get(position % imageList.size()));rn return imageList.get(position % imageList.size());rn rn rn @Overridern public boolean isViewFromObject(View arg0, Object arg1) rn return arg0 == arg1;rn rn rn @Overridern public void destroyItem(ViewGroup container, int position, Object object) rn container.removeView((View) object);rn object = null;rn rn rn rn rn rn rn
fragment嵌套fragment不显示问题(viewpager)
小伙伴们有没有遇到过这个问题呢? 不多废话,上我的解决办法: 我们在new PagerAdapter的时候如果是用MyPagerAdapter mAdapter = new MyPagerAdapter(mycontext.getSupportFragmentManager(), mFragmentList, mycontext);或者是: MyPagerAdapter mAdapter = n
Android软件架构之RadioGroup + Fragment , TabLayout + ViewPager +Fragment
Android软件架构之RadioGroup + Fragment , TabLayout + ViewPager + Fragment 覆盖市场大部分商业软件架构 仿今日头条等APP主流架构
相关热词 c# login 居中 c# 考试软件 c# 自然语言分析 c# 分段读取文件 c# 泛型反射 c#打断点 c# 时间转多少秒 c# 线程函数加参数 c# modbus 读取 c#查询集合表