Java 使用意图从另一个片段调用一个片段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25945613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:34:08  来源:igfitidea点击:

Using intent to call a fragment from another fragment

javaandroidandroid-intentandroid-fragments

提问by user3852672

I am using a viewpager control to host three fragments.I have placed a button in each fragment to go to the next fragment.So i wanted to know as how to go from one fragment to another using intent?

我正在使用 viewpager 控件来承载三个片段。我在每个片段中放置了一个按钮以转到下一个片段。所以我想知道如何使用意图从一个片段转到另一个片段?

The main purpose is to create a sign up form which has been divided into three fragments.The code is shown below:

主要目的是创建一个已被分为三个片段的注册表单。代码如下所示:

The main activity:

主要活动:

package pl.looksok.viewpagerdemo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class MainActivity extends FragmentActivity {
    ViewPager pager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
         pager = (ViewPager)findViewById(R.id.myViewPager);
        pager.setAdapter(pageAdapter);

    }

}

The first fragment:

第一个片段:

package pl.looksok.viewpagerdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.Fragment;

public class FragmentBlue extends Fragment {
Button btnnext1;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_blue, container, false);
        btnnext1=(Button) view.findViewById(R.id.btnnext1);

        btnnext1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                 Intent intent = new Intent(view.getContext(), FragmentGreen.class);
                    view.getContext().startActivity(intent);
                    getActivity().finish();

            }
        });

        return view;
    }
}

The second fragment:

第二个片段:

package pl.looksok.viewpagerdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.Fragment;

public class FragmentGreen extends Fragment {
Button btnnext2;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_green, container, false);
        btnnext2=(Button) view.findViewById(R.id.btnnext2);
        btnnext2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), FragmentPink.class);
                view.getContext().startActivity(intent);
                getActivity().finish();

            }
        });
        return view;
    }
}

The third fragment:

第三个片段:

package pl.looksok.viewpagerdemo;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.Fragment;

public class FragmentPink extends Fragment {
Button btnnext3;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_pink, container, false);
        btnnext3=(Button) view.findViewById(R.id.btnnext3);
        btnnext3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


            }
        });
        return view;
    }
}

The adapter for the viewpager:

viewpager 的适配器:

package pl.looksok.viewpagerdemo;

import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
        this.fragments = new ArrayList<Fragment>();
        fragments.add(new FragmentBlue());
        fragments.add(new FragmentGreen());
        fragments.add(new FragmentPink());
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

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

The custom class for the viewpager:

viewpager 的自定义类:

package pl.looksok.viewpagerdemo;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class CustomViewPager extends ViewPager {

    private boolean isPagingEnabled = false;

    public CustomViewPager(Context context) {
        super(context);
    }

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

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onInterceptTouchEvent(event);
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }
}

The code which i am using now shows the following error on clicking the first button:

我现在使用的代码在单击第一个按钮时显示以下错误:

09-20 10:54:18.632: E/AndroidRuntime(9401): FATAL EXCEPTION: main
09-20 10:54:18.632: E/AndroidRuntime(9401): android.content.ActivityNotFoundException: Unable to find explicit activity class {pl.looksok.viewpagerdemo/pl.looksok.viewpagerdemo.FragmentGreen}; have you declared this activity in your AndroidManifest.xml?
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1405)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1379)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.app.Activity.startActivityForResult(Activity.java:2827)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:824)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.app.Activity.startActivity(Activity.java:2933)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at pl.looksok.viewpagerdemo.FragmentBlue.onClick(FragmentBlue.java:25)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.view.View.performClick(View.java:2538)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.view.View$PerformClick.run(View.java:9152)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.os.Handler.handleCallback(Handler.java:587)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.os.Looper.loop(Looper.java:130)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at android.app.ActivityThread.main(ActivityThread.java:3689)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at java.lang.reflect.Method.invokeNative(Native Method)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at java.lang.reflect.Method.invoke(Method.java:507)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
09-20 10:54:18.632: E/AndroidRuntime(9401):     at dalvik.system.NativeStart.main(Native Method)

So the question is how to use intent in between fragments.Is there a better way to divide the sign up form into three parts without using viewpager?

所以问题是如何在片段之间使用意图。有没有更好的方法将注册表单分为三个部分而不使用viewpager?

采纳答案by SMR

If all the fragments are within the same ViewPager and you just want to be navigated to that fragment then you dont need any Intents. all you need to is :

如果所有片段都在同一个 ViewPager 中并且您只想导航到该片段,那么您不需要任何Intents. 所有你需要的是:

mViewPager.setCurrentItem(POSITION, true);

here POSITION is an integer.

这里 POSITION 是一个整数。

Now the view pager is in Activitybut the Buttonis inside Fragmentso you need to do this create this method inside your activity

现在的观点寻呼机是在Activity,但Button在里面Fragment,所以你需要做的创建活动中这种方法

public void selectFragment(int position){
mViewPager.setCurrentItem(position, true); 
// true is to animate the transaction
}

and call like this inside your OnClickListener:

并在您的内部调用这样的OnClickListener

((MainActivity)getActivity()).selectFragment(POSITION_YOU_WANNA_SELECT);

Hope it helps.

希望能帮助到你。

回答by Piyush

You can't call your Fragment like this,

你不能这样调用你的 Fragment,

  Intent intent = new Intent(view.getContext(), FragmentGreen.class);
  view.getContext().startActivity(intent);
  getActivity().finish();

you need to call your fragment like this way

你需要像这样调用你的片段

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    FragmentGreen llf = new FragmentGreen();
    ft.replace(R.id.listFragment, llf);
    ft.commit();

Intentis basically used for call one activity from another. For add new Fragmentyou can't use Intent. For that you have to use FragmentManagerand for open fragment FragmentTransaction.

Intent基本上用于从另一个活动调用一个活动。对于添加新的,Fragment您不能使用Intent. 为此,您必须使用FragmentManager和打开 fragment FragmentTransaction

for more details go Here

欲了解更多详情,请点击此处

回答by Nay Linn

FragmentManager fm=getFragmentManager();
fm.beginTransaction().replace(R.layout.fragment_blue, (Fragment)new FragmentGreen()).commit();
getActivity().getActionBar().setTitle("Home");

回答by AminFeizi

public class Fragment3 extends Fragment{

公共类 Fragment3 扩展 Fragment{

Button button;
@Nullable
@Override
public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view;
    Fragment fragment;
    view = inflater.inflate(R.layout.page_4, container, false);
    button=view.findViewById(R.id.exit);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager fm = getFragmentManager();
            assert fm != null;
            FragmentTransaction ft = fm.beginTransaction();
            FragmentLogin llf = new FragmentLogin();
            ft.replace(R.id.FrameButton, llf);
            ft.commit();
        }


    });



    return view;


}

}

}