简体   繁体   English

如何在Android中单击按钮之间在片段之间切换?

[英]How to switch between fragments from button click in android?

I am creating an Android app. 我正在创建一个Android应用。 It contains two activities. 它包含两个活动。 One for login and the other for registration. 一个用于登录,另一个用于注册。 Both of them are in separate tabs and I can switch between them by swiping. 它们都位于单独的标签中,我可以通过滑动来在它们之间切换。

But there is a button on bottom of both tabs, in case of login is necessary. 但是,如果需要登录,则两个选项卡的底部都有一个按钮。 I need to move to registration tab when the button is clicked, and also another button to return to login tab. 单击该按钮时,我需要移至注册选项卡,还要单击另一个按钮以返回登录选项卡。

How can I implement it using onclick listener event? 如何使用onclick监听器事件实现它?

public static class PlaceholderFragment extends Fragment {

    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }
    private static final String lTAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText linputEmail;
    private EditText linputPassword;
    private ProgressDialog lpDialog;
    private SessionManager lsession;
    private SQLiteHandler ldb;
    private static final String rTAG = RegisterActivity.class.getSimpleName();
    private Button btnRegister;
    private Button btnLinkToLogin;
    private EditText rinputFullName;
    private EditText rinputEmail;
    private EditText rinputPassword;
    private ProgressDialog rpDialog;
    private SessionManager rsession;
    private SQLiteHandler rdb;
     public static Context context;

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

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

        if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {

            View rootView = inflater.inflate(R.layout.activity_login, container, false);
            linputEmail = (EditText) rootView.findViewById(R.id.email);
            linputPassword = (EditText) rootView.findViewById(R.id.password);
            btnLogin = (Button) rootView.findViewById(R.id.btnLogin);
            btnLinkToRegister = (Button) rootView.findViewById(R.id.btnLinkToRegisterScreen);

            // Progress dialog
            lpDialog = new ProgressDialog(getActivity());
            lpDialog.setCancelable(false);

            // SQLite database handler
             context=getContext();
            ldb = new SQLiteHandler(context);

            // Session manager
            lsession = new SessionManager(context);

            // Check if user is already logged in or not
            if (lsession.isLoggedIn()) {
                // User is already logged in. Take him to main activity
                Intent intent = new Intent(context, MainActivity.class);
                startActivity(intent);
                getActivity().finish();
            }

            // Login button Click Event
            btnLogin.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    String email = linputEmail.getText().toString().trim();
                    String password = linputPassword.getText().toString().trim();


                    // Check for empty data in the form
                    if (!email.isEmpty() && !password.isEmpty()) {
                        // login user
                        checkLogin(email, password);
                    } else {
                        // Prompt user to enter credentials
                        Toast.makeText(context,
                                "Please enter the credentials!", Toast.LENGTH_LONG)
                                .show();
                    }
                }

            });

            // Link to Register Screen
            btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {

                    Intent i = new Intent(context,
                            RegisterActivity.class);
                    startActivity(i);
                    getActivity().finish();
                }
            });
            return  rootView;
        }

        else if (getArguments().getInt(ARG_SECTION_NUMBER)==2){

            View rootView = inflater.inflate(R.layout.activity_register, container, false);
            rinputFullName = (EditText) rootView.findViewById(R.id.name);
            rinputEmail = (EditText) rootView.findViewById(R.id.email);
            rinputPassword = (EditText) rootView.findViewById(R.id.password);
            btnRegister = (Button) rootView.findViewById(R.id.btnRegister);
            btnLinkToLogin = (Button) rootView.findViewById(R.id.btnLinkToLoginScreen);

            // Progress dialog
            rpDialog = new ProgressDialog(getActivity());
            rpDialog.setCancelable(false);

            // Session manager
            context=getContext();
            rsession = new SessionManager(context);

            // SQLite database handler
            rdb = new SQLiteHandler(context);

            // Check if user is already logged in or not
            if (rsession.isLoggedIn()) {
                // User is already logged in. Take him to main activity
                Intent intent = new Intent(context,
                        MainActivity.class);
                startActivity(intent);
                getActivity().finish();
            }

            // Register Button Click event
            btnRegister.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    String name = rinputFullName.getText().toString().trim();
                    String email = rinputEmail.getText().toString().trim();
                    String password = rinputPassword.getText().toString().trim();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                        if(isEmailValid(email)) {
                            registerUser(name, email, password);
                        }else{
                            Toast.makeText(context,
                                    "Please enter valid email!", Toast.LENGTH_LONG)
                                    .show();
                        }
                    } else {
                        Toast.makeText(context,
                                "Please enter your details!", Toast.LENGTH_LONG)
                                .show();
                    }
                }
            });

            // Link to Login Screen
            btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Intent i = new Intent(context,
                            LoginActivity.class);
                    startActivity(i);
                    getActivity().finish();
                }
            });

            return  rootView;

        }
        return null;
    }
    ``
/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "LOGIN";
            case 1:
                return "REGISTER";

        }
        return null;
    }
}

There is a two possibility for this scenario :- 这种情况有两种可能性:

  1. If you want to switch one fragment to another fragment then you have to use framelayout instead of viewpager. 如果要将一个片段切换到另一个片段,则必须使用framelayout而不是viewpager。
  2. if you use framelayout then you can not swipe tabs .you have to click tabs to change it. 如果使用framelayout,则无法滑动选项卡。必须单击选项卡才能对其进行更改。

    after use of framelayout you can get famelayout id from the main activity and you can use FragmentTransaction to switch fragment. 使用framelayout后,您可以从主要活动中获取famelayout ID,还可以使用FragmentTransaction切换片段。

    On Button Click in Fragment 在按钮上单击片段

      FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.framelayout, new TwoFragment(), "NewFragment TAG"); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); 

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

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