【问题标题】:Need to save user's name via AlertDialog that shows only once需要通过仅显示一次的 AlertDialog 保存用户名
【发布时间】:2013-03-02 01:50:11
【问题描述】:

我有一个 AlertDialog,它会在按下按钮时显示;按下警报“完成”按钮时保存用户名;然后将用户移动到另一个活动。我想弄清楚的是如何仅在第一次按下显示 AlertDialog 的布局按钮时显示 AlertDialog,这样当用户回到应用程序的这一部分并按下相同的布局按钮时,AlertDialog不显示,用户不必再次输入他们的名字。这是不起作用的代码:

    public class CloseoutActivity extends Activity {

SharedPreferences prefs2;
String prefs2String="";
boolean firstRun = true;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_closeout);

 // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
    }


}

public void closeoutCashButtonPressed (View closeoutCashButtonPressedView){

if(firstRun){   

     AlertDialog.Builder builder3 = new AlertDialog.Builder(this);
     builder3.setTitle("    Please enter your full name");
     final EditText input3 = new EditText(this);
     input3.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_WORDS|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
     builder3.setView(input3);
     builder3.setPositiveButton("Done", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            prefs2String = input3.getText().toString();

            prefs2 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            SharedPreferences.Editor prefs2Editor = prefs2.edit();
            String userName1 = input3.getText().toString();
            prefs2Editor.putString("userName", userName1);
            prefs2Editor.commit();

            launchIntent1();

        }
    });

    builder3.show();
}

firstRun = false;



}

public void launchIntent1(){

    Intent displayCloseoutCashButtonSignal = new Intent (this, CloseoutCashButtonSignal.class);
    displayCloseoutCashButtonSignal.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(displayCloseoutCashButtonSignal);

使用此代码,当我回到应用程序的这一部分时,AlertDialog 会不断弹出。有任何想法吗?谢谢!

【问题讨论】:

    标签: android android-alertdialog


    【解决方案1】:

    您需要将firstRun 标志存储在SharedPrefs 或其他一些永久存储中。每次运行 Activity 时,您的标志将是 true 否则。如果这是您存储username 的唯一位置,那么您应该能够简单地检查SharedPrefs 名称是否存在,如果存在则继续按您的需要,但如果不存在则您可以添加名称并显示Dialog

    【讨论】:

    • 不客气!希望对你有效。感谢您接受答案,但您应该确保它在将来首先起作用,以防回答者遗漏了什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多