i have two fragments of the same activity(navigation drawer) i added a button on one among them to switch to another but i am getting an error.i don't know how this works . please help me
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
SwitchBtn= (AppCompatButton) rootView.findViewById(R.id.btnswitch);
// Register Button Click event
SwitchBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(getActivity(),
FriendsFragment.class);
getActivity().startActivity(intent);
}
});
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
}
You're switching between fragments, not starting a new activity. Replace this
Intent intent = new Intent(getActivity(),
FriendsFragment.class);
getActivity().startActivity(intent);
With this
getFragmentManager().beginTransaction()
.replace(R.id.your_container_id, new FriendsFragment())
.commit()
You can't open a fragment as such. What you need to do is either create them on the same activity, use a 'screen' variable that controls display by using the .setVisible on your components.
Or, what you can do is put your fragments on different activities using intent.
private Content C = getApplicationContext();
Intent myIntent = new Intent(C,yourActivity.class);
C.startActivity(myIntent);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.