Android中自定义的类怎样使用context
时间: 2024-04-29 08:22:22 浏览: 11
在 Android 中,我们可以通过传递 Context 对象来实现自定义类中使用 Context 的功能。一般情况下,我们可以在自定义类的构造函数中接收 Context 参数,并将其存储为类成员变量。然后,在需要使用 Context 的地方,我们可以使用这个成员变量来获取系统资源或执行特定的操作。
例如,下面的代码演示了一个自定义类 MyCustomClass,它接收一个 Context 参数并使用它来获取系统资源:
```
public class MyCustomClass {
private Context mContext;
public MyCustomClass(Context context) {
this.mContext = context;
}
public void doSomething() {
// 使用 mContext 获取系统资源或执行特定操作
Resources res = mContext.getResources();
String appName = res.getString(R.string.app_name);
Toast.makeText(mContext, "Hello from " + appName, Toast.LENGTH_SHORT).show();
}
}
```
在调用 MyCustomClass 的时候,我们需要传递一个正确的 Context 参数:
```
MyCustomClass custom = new MyCustomClass(this); // this 表示当前 Activity 的 Context
custom.doSomething();
```
这样,MyCustomClass 就能够在需要的时候使用传递进来的 Context 对象了。