Androd 自定义类如何获取Context
时间: 2023-06-16 16:08:35 浏览: 40
在 Android 中,可以通过以下方式获取 Context:
1. 在 Activity 中,可以直接使用 `this` 关键字获取 Context。
2. 在 Fragment 中,可以通过 `getContext()` 方法获取 Context。
3. 在自定义 View 中,可以通过重写 `View` 类的构造函数,并将 Context 作为参数传入来获取 Context。
4. 在 Service 或 BroadcastReceiver 中,可以通过 `getApplicationContext()` 方法获取全局 Context。
需要注意的是,如果获取的 Context 是 Activity 的 Context,使用时需要注意内存泄漏问题,避免在 Activity 销毁后仍然持有该 Context。建议使用 Application Context 或 Application 对象来代替 Activity Context。
相关问题
Android中自定义的类怎样使用context
在 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 对象了。
android获取自定义属性,android 自定义View中获取系统属性
要获取自定义属性,可以使用TypedArray类。在自定义View的构造函数中,可以通过context.obtainStyledAttributes(attrs, R.styleable.CustomView)方法获取TypedArray对象,然后使用TypedArray的getXXX()方法获取自定义属性的值,其中XXX表示属性的数据类型。例如,获取一个自定义属性名为customAttr的字符串值,可以使用以下代码:
```java
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
String customAttrValue = a.getString(R.styleable.CustomView_customAttr);
a.recycle();
```
要获取系统属性,可以使用android.R.styleable类。例如,获取android:textColor属性的值,可以使用以下代码:
```java
TypedArray a = context.obtainStyledAttributes(attrs, android.R.styleable.TextView);
int textColor = a.getColor(android.R.styleable.TextView_textColor, Color.BLACK);
a.recycle();
```
其中,android.R.styleable.TextView表示TextView控件的所有属性,a.getColor()方法获取颜色值,Color.BLACK指定了当属性值不存在时的默认值。注意,在获取系统属性时,需要使用系统的R类,即android.R。