如何将一个片段移动到android中的另一个片段

时间:2017-01-11 06:21:36

标签: java android android-fragments

我正在开发一个包含片段的应用。我无法将一个片段移动到另一个片段。

当我使用此代码时(android value passing from fragment to fragment using recyclerview not working引用)

    SpeedDialFragment fragobj  = new SpeedDialFragment();
    Bundle bundle=new Bundle();
    bundle.putString("message", "From Activity");
    fragobj.setArguments(bundle);
    switchFragment(R.layout.fragment_page, fragobj);

它不起作用。

我的代码如下所示。

MainActivity java:

public class MainActivity extends AppCompatActivity implements PageFragment.OnFragmentInteractionListener {
    ViewPager viewPage;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        startService(new Intent(this, LockScreenService.class));
    }

    private void initView() {
        initViewPager();
    }

    private void initViewPager() {
        viewPage = (ViewPager) this.findViewById(R.id.viewpage);
        viewPage.setOffscreenPageLimit(3);
        viewPage.setCurrentItem(1);
        viewPage.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override public Fragment getItem(int position) {
                if (position < 2) {
                    return PageFragment.newInstance("", "");
                } else {
                    return new AmapFragment();
                }
            }

            @Override public int getCount() {
                return 3;
            }
        });
    }

    @Override public void onFragmentInteraction(Uri uri) {
    }

    public void loadFragment(int id, Fragment fragment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(id, fragment, fragment.toString());
        ft.addToBackStack(null);
        ft.commit();
    }
    }

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.happiness.lockscreen.MainActivity"
    >
    <android.support.v4.view.ViewPager
    android:id="@+id/viewpage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ></android.support.v4.view.ViewPager>
    </RelativeLayout>

fragment_page.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
  android:text="Speed Dial"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/buttonSpeedDial" />
</FrameLayout>

PageFragment.java

public class PageFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;

    Button button;
    Context context;

    private OnFragmentInteractionListener mListener;
    public PageFragment() {

    }

    public static PageFragment newInstance(String param1, String param2) {
    PageFragment fragment = new PageFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
    }

    @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
      mParam1 = getArguments().getString(ARG_PARAM1);
      mParam2 = getArguments().getString(ARG_PARAM2);
    }
    }

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment


    View view = inflater.inflate(R.layout.fragment_page, container, false);

    button = (Button) view.findViewById(R.id.buttonSpeedDial);

    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Log.d("SpeedDialFragment", "clicked : ");
        /*SpeedDialFragment fragment = new SpeedDialFragment(); // replace your custom fragment class
        Bundle bundle = new Bundle();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        bundle.putString("key","value"); // use as per your need
        fragment.setArguments(bundle);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(viewID,fragment);
        fragmentTransaction.commit();*/

        SpeedDialFragment fragobj  = new SpeedDialFragment();
        Bundle bundle=new Bundle();
        bundle.putString("message", "From Activity");
        fragobj.setArguments(bundle);
        switchFragment(R.layout.fragment_page, fragobj);
      }
    });
    return view;
    }
    public void switchFragment(int id, Fragment fragment) {
    if (context == null)
      return;
    if (context instanceof MainActivity) {
      MainActivity mainActivity = (MainActivity) context;
      mainActivity.loadFragment(id, fragment);
    }
    }
    public void onButtonPressed(Uri uri) {
    if (mListener != null) {
      mListener.onFragmentInteraction(uri);
    }
    }

    @Override public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
      mListener = (OnFragmentInteractionListener) context;
    } else {
      throw new RuntimeException(
          context.toString() + " must implement OnFragmentInteractionListener");
    }
    }

    @Override public void onDetach() {
    super.onDetach();
    mListener = null;
    }

    public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
    }
}

请帮帮我。

SpeedDialFragment.java
public class SpeedDialFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public SpeedDialFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment PageFragment.
 */
// TODO: Rename and change types and number of parameters
public static PageFragment newInstance(String param1, String param2) {
    PageFragment fragment = new PageFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                   Bundle savedInstanceState) {

    String strtext=getArguments().getString("message");
    Log.d("SpeedDialFragment", "strtext : "+strtext);
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_speeddial, container, false);
}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(
                context.toString() + " must implement OnFragmentInteractionListener");
    }
}

@Override public void onDetach() {
    super.onDetach();
    mListener = null;
}


 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}
}

1 个答案:

答案 0 :(得分:0)

if(context==null) return;您尚未初始化上下文对象。 试试这个

public void switchFragment(int id, Fragment fragment) {

    if (getActivity() instanceof MainActivity) {
      MainActivity mainActivity = (MainActivity) getActivity();
      mainActivity.loadFragment(id, fragment);
    }
}