How to pass a boolean between intents

前端 未结 3 1182
轻奢々
轻奢々 2020-12-06 00:43

I need to pass a boolean value to and intent and back again when the back button is pressed. The goal is to set the boolean and use a conditional to prevent multiple launche

相关标签:
3条回答
  • 2020-12-06 00:58

    have a private member variable in your activity called wasShaken.

    private boolean wasShaken = false;
    

    modify your onResume to set this to false.

    public void onResume() { wasShaken = false; }
    

    in your onShake listener, check if it's true. if it is, return early. Then set it to true.

      public void onShake() {
                  if(wasShaken) return;
                  wasShaken = true;
                              // This code is launched multiple times on a vigorous
                              // shake of the device.  I need to prevent this.
                  Intent myIntent = new Intent(MyApp.this, NextActivity.class);
                  MyApp.this.startActivity(myIntent);
      }
    });
    
    0 讨论(0)
  • 2020-12-06 01:03

    This is how you do it in Kotlin :

    val intent = Intent(this@MainActivity, SecondActivity::class.java)
                intent.putExtra("sample", true)
                startActivity(intent)
    
    var sample = false
    sample = intent.getBooleanExtra("sample", sample)
    println(sample)
    

    Output sample = true

    0 讨论(0)
  • 2020-12-06 01:23

    Set intent extra(with putExtra):

    Intent intent = new Intent(this, NextActivity.class);
    intent.putExtra("yourBoolName", true);
    

    Retrieve intent extra:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName");
    }
    
    0 讨论(0)
提交回复
热议问题