简体   繁体   English

如何在android java中使用intent切换到相同活动的两个片段

[英]How to switch to two fragments of the same activity using intent in android java

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. 您需要做的是在同一个活动上创建它们,使用一个“屏幕”变量,通过使用组件上的.setVisible来控制显示。

Or, what you can do is put your fragments on different activities using intent. 或者,您可以做的是使用intent将您的片段放在不同的活动上。

private Content C = getApplicationContext();
Intent myIntent = new Intent(C,yourActivity.class);
C.startActivity(myIntent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM