我很新的Android/Java工作,請耐心等待。代碼中的參考從Activity移動到Fragment不再解決
我將代碼從LoginActivity > onCreate
移到我創建FragmentLogin
的方法onCreate
中,其中許多類不再解析,如findViewById
。我假設我沒有正確傳遞容器活動的上下文。
或某些其他新手的錯誤...
這裏是LoginActivity.java [相關部分複製]
public class LoginActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize Fragments //
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
setContentView(R.layout.fragment_login);
}
}
和FragmentLogin.java:
public class FragmentLogin extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
final ValidationManager Check = new ValidationManager();
final SessionManager Session = new SessionManager(this);
final EditText textEmail = (EditText) findViewById(R.id.login_email);
final EditText textPassword = (EditText) findViewById(R.id.login_pass);
final Button buttonLogIn = (Button) findViewById(R.id.button_login);
final Button buttonSignup = (Button) findViewById(R.id.button_signup);
// Listen for FORGOTTEN PASSWORD click event, open ForgottenPassword Fragment //
final Button forgottenPassword = (Button) findViewById(R.id.button_lost_pass);
forgottenPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.fragment_forgotten_password);
}
});
... more code ...
}
}
的變量/方法是當第二個代碼塊位於活動的onCreate
方法中但在將代碼移動到之後不再解析所述FragmentLogin
片段類的210:
findViewById
,setContentView
基本上,這是一個登錄表單其中默認片段應login
,和該頁面(Button forgottenPassword
)上的按鈕將打開另一個片段(FragmentForgottenPassword
)。
誰能告訴我我做錯了什麼?
你的分段事務沒有被提交,你必須執行'''beginTransaction().add/replace/.commit()''','''''setContentView''' super.onCreate'''。 – danypata