简体   繁体   中英

change fragment layout programmatically

I have two tabs, which are fragments, and one is for login (login fragment). After it clicks login, a new activity (login activity) will pop up, and then the user needs to login. If he has successfully logged in, the login activity will be closed by using finish() . And then I want to change the layout of the tab from login fragment to welcome fragment, using onActivityResult() .

I have two layouts created, login fragment layout and welcome fragment layout. However, I do not know how to change the layout since setContentView() cannot be used.

public class UserLoginTab extends Fragment {

String username = "";

Button loginButton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.user_login_tab, container, false);

    loginButton = (Button) rootView.findViewById(R.id.btn_login);
    loginButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivityForResult(intent, 1);
        }
    });


    return rootView;
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if(resultCode == RESULT_OK){
            username=data.getStringExtra("username");
            //change layout here and add the username to a textView
            //The layout is (R.layout.welcome_tab)
        }
    }
}


}

Suppose you have two XML layout files: login.xml and welcome.xml . For each XML layout file, you should create a class which extends Fragment : LoginFragment and WelcomeFragment . Then in the FragmentPagerAdapter subclass, write some logic which decides which of these two fragments to display. You could have some kind of loggedIn flag, possibly stored in SharedPreferences which indicates whether or not the user is already logged in.

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.

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