Unable to switch from Fragment to Activity / Activity to Fragment in Android Programming

感情迁移 提交于 2020-01-01 19:06:23

问题


Currently, I am mainly using Fragments to connect to Facebook.

However, for the other codes, I am using normal activites (no Fragments).

My issue now is that I wish to have a button to link from my "Home Page" to the Fragment, and from the Fragment back to my "Home Page"

I am unable to do so.

I tried to use the same code to switch between activities for this but it does not work.

Is there a way to Link Normal Activities to Fragments and Vice Versa ? Or can they only link to each other ?

This is my Code:

    public class SplashFragment extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState) {
    View view = inflater.inflate(R.layout.splash, container, false);
//   return view;

    Button btnNextScreen = (Button) view.findViewById(R.id.btnNextScreen);      
//    Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);

    //Listening to button event
    btnNextScreen.setOnClickListener(new View.OnClickListener() {

      public void onClick(View arg0) {
          //Starting a new Intent
          Intent nextScreen = new Intent(**getApplicationContext()**, SecondScreenActivity.class);
            startActivity(nextScreen);

}
});

 return view;   
}
}

I am getting an error at getApplicationContext().

If I change it to getActivity(), they will prompt with another error that they are expecting to switch to a Fragment, not an activity.

Thank you for your help !

Regards, AndroidStudent


回答1:


use this getActivity() if u want to navigate from fragment to activity.

Intent nextScreen = new Intent(getActivity(), SecondScreenActivity.class);
startActivity(nextScreen);



回答2:


do like this:

Intent i = new Intent(getActivity(), activityname.class); 
i.putExtra("key", value);           
getActivity().startActivity(i);


来源:https://stackoverflow.com/questions/13795433/unable-to-switch-from-fragment-to-activity-activity-to-fragment-in-android-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!