[英]change fragment layout programmatically
我有兩個選項卡,它們是片段,一個用於登錄(登錄片段)。 單擊登錄后,將彈出一個新活動(登錄活動),然后用戶需要登錄。 如果他已經成功登錄,則將使用finish()
關閉登錄活動。 然后,我想使用onActivityResult()
將選項卡的布局從登錄片段更改為歡迎片段。
我創建了兩個布局,登錄片段布局和歡迎片段布局。 但是,由於無法使用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)
}
}
}
}
假設您有兩個XML布局文件: login.xml
和welcome.xml
。 對於每個XML布局文件,你應該創建延伸的一類Fragment
: LoginFragment
和WelcomeFragment
。 然后,在FragmentPagerAdapter
子類中,編寫一些邏輯來決定要顯示這兩個片段中的哪一個。 您可能有某種loggedIn
標志,可能存儲在SharedPreferences
,該標志指示用戶是否已經登錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.