showToast封装
时间: 2023-10-20 22:27:17 浏览: 90
Sure! Here's an example of how you can create a `showToast` function for displaying toast messages in your Android application:
```java
import android.content.Context;
import android.widget.Toast;
public class MyUtils {
public static void showToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
```
In this example, we define a static method `showToast` within a utility class called `MyUtils`. The method takes two parameters: a `Context` object and a `String` message. It uses the `Toast.makeText` method to create a toast message with the provided context and message. The duration of the toast is set to `Toast.LENGTH_SHORT`, but you can also use `Toast.LENGTH_LONG` for a longer duration.
To use this `showToast` function in your code, you would simply call it like this:
```java
MyUtils.showToast(context, "Hello, world!");
```
Make sure to replace `context` with the appropriate context object in your code and `"Hello, world!"` with your desired message.
This `showToast` function can be used to display short informational messages to the user in your Android app.
阅读全文