我有MainActivity其中有3個片段,我想從MainActivity中的片段之一切換到Activity2,但我的嘗試總是失敗。當我按下第三個片段中的按鈕ok將我連接到Activity2時,我的應用程序崩潰。我正在研究我在一篇教程中找到的代碼。先謝謝你!從片段android啓動活動錯誤
public class ProfileFragment extends Fragment implements View.OnClickListener {
private TextView tv_name,tv_email,tv_message;
private SharedPreferences pref;
private AppCompatButton btn_change_password,btn_logout, btn_ok;
private EditText et_old_password,et_new_password;
private AlertDialog dialog;
private ProgressBar progress;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile,container,false);
initViews(view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
pref = getActivity().getPreferences(0);
tv_name.setText("Здравей, "+pref.getString(Constants.NAME,"")+"!");
tv_email.setText(pref.getString(Constants.EMAIL,""));
btn_ok=(AppCompatButton)view.findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getActivity(),activity2.class);
startActivity(intent);
}
});
}
private void initViews(View view){
tv_name = (TextView)view.findViewById(R.id.tv_name);
tv_email = (TextView)view.findViewById(R.id.tv_email);
btn_change_password = (AppCompatButton)view.findViewById(R.id.btn_chg_password);
btn_logout = (AppCompatButton)view.findViewById(R.id.btn_logout);
btn_ok=(AppCompatButton)view.findViewById(R.id.btn_ok);
btn_change_password.setOnClickListener(this);
btn_logout.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_chg_password:
showDialog(); //I deleted this method from the code, it doesnt have a lot in common with my question
break;
case R.id.btn_logout:
logout();
break;
}
private void logout() {
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,false);
editor.putString(Constants.EMAIL,"");
editor.putString(Constants.NAME,"");
editor.putString(Constants.UNIQUE_ID,"");
editor.apply();
goToLogin();
}
private void goToLogin(){
Fragment login = new LoginFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,login);
ft.commit();
}
}
什麼是你的錯誤,你有沒有在聲明活性2明顯嗎? –
你可以顯示R.layout.fragment_profile? –
您的片段已經實現的onclick監聽器添加這對開關狀態 '情況R.id.btn_logout: 意向意圖=新意圖(getActivity(),activity2.class); startActivity(intent); 突破;' –