[英]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()
. 如果他已经成功登录,则将使用
finish()
关闭登录活动。 And then I want to change the layout of the tab from login fragment to welcome fragment, using onActivityResult()
. 然后,我想使用
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. 但是,由于无法使用
setContentView()
,因此我不知道如何更改布局。
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
. 假设您有两个XML布局文件:
login.xml
和welcome.xml
。 For each XML layout file, you should create a class which extends Fragment
: LoginFragment
and WelcomeFragment
. 对于每个XML布局文件,你应该创建延伸的一类
Fragment
: LoginFragment
和WelcomeFragment
。 Then in the FragmentPagerAdapter
subclass, write some logic which decides which of these two fragments to display. 然后,在
FragmentPagerAdapter
子类中,编写一些逻辑来决定要显示这两个片段中的哪一个。 You could have some kind of loggedIn
flag, possibly stored in SharedPreferences
which indicates whether or not the user is already logged in. 您可能有某种
loggedIn
标志,可能存储在SharedPreferences
,该标志指示用户是否已经登录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.