getIntExtra()
时间: 2023-11-12 21:05:12 浏览: 80
getIntExtra() is a method in the Android SDK's Intent class that retrieves an integer value from an Intent object. It is commonly used to pass data between Activities or Services in an Android application. getIntExtra() takes two parameters: the name of the extra data as a string, and a default value to return if the extra data is not found.
For example, if an Activity needs to pass an integer value to another Activity, it can create an Intent object and use putExtra() to add the value to the Intent. The receiving Activity can then use getIntExtra() to retrieve the value.
Here's an example of how to use getIntExtra():
```
// Sender Activity
Intent intent = new Intent(SenderActivity.this, ReceiverActivity.class);
int value = 42;
intent.putExtra("myIntExtra", value);
startActivity(intent);
// Receiver Activity
int defaultValue = 0;
int receivedValue = getIntent().getIntExtra("myIntExtra", defaultValue);
```
In this example, the Sender Activity creates an Intent object and adds an integer value of 42 to it using putExtra(). It then starts the Receiver Activity with this Intent.
In the Receiver Activity, the getIntExtra() method is used to retrieve the integer value from the Intent. The first parameter is the name of the extra data ("myIntExtra"), and the second parameter is the default value to return if the extra data is not found (in this case, 0). The retrieved value is assigned to the variable "receivedValue".
阅读全文