单击警告对话框中的按钮后导航到下一个活动(单击注销首选项后出现)

时间:2017-08-13 07:03:09

标签: android android-intent dialog preferences

通过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;
            }
        });

    }

  }

}

2 个答案:

答案 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课程。