通过Intent
导航到下一个活动时出现问题。
错误是:
“无法解析构造函数'Intent(anonymous.android.content.DialogInterface.OnClickListener,java lang.Class)”
我必须通过点击退出按钮导航回登录屏幕。
以下是我的代码:
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SettingsFragment settingsFragment = new SettingsFragment();
fragmentTransaction.add(android.R.id.content,settingsFragment, "SETTINGS_FRAGMENT");
fragmentTransaction.commit();
}
public static class SettingsFragment extends PreferenceFragment {
public void onClick(){
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(getResources().getString(R.string.log_out));
//Set up your AlertDialog and buttons
alert.setMessage(getResources().getString(R.string.are_you_sure_you_want_to_log_out_of_yoqa));
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(this,LoginActivity.class);
startActivity(i);
}
});
alert.setCancelable(true);
alert.show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_settings);
Preference myPref = findPreference("logout");
myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
onClick();
return true;
}
});
}
}
}
答案 0 :(得分:1)
替换
Intent i = new Intent(this,LoginActivity.class);
与
Intent i = new Intent(SettingsFragment.this.getActivity(), LoginActivity.class);
答案 1 :(得分:0)
您正在Fragment
导航。因此,从Fragment
开始,您获得context
并使用activity
开始getActiviy()
。
改变这个:
Intent i = new Intent(this,LoginActivity.class);
使用:
Intent i = new Intent(getActivity(), LoginActivity.class);
您必须在activity
文件中注册AndroidManifest
课程。