Android 在自定义类中调用xml文件中的数据

Android 在自定义类中调用xml文件的数据

一般调用xml文件中的数据的时候,都是在Activity中进行调用,而在Activity中读取res路径下的xml文件数据的方法一般是:(这里以读取string.xml数据举例)

getResources().getString(R.string.app_name);

还有不同的读取方法,这里不在赘述。
但是在自定义类中,如果没有Context,就没有getResources()方法,也就没办法使用xml文件。
那么可以在activity调用时可以将Context作为参数传递给自定义类中的方法:
Activity中调用,使用getBaseContext()获取Context:

CalMo cm = new CalMo();
cm.ReadName(this.getBaseContext());

然后就可以直接在自定义类中的方法如Activity中操作一样进行读取

String ReadName(Context ct){
	return ct.getResources().getString(R.string.app_name);
}

ps:我在实际一开始使用时,想在实例化时直接通过构造函数将Context传给类中的成员,但是后来在从一个Activity传递实例化对象到另一个Activity时发现,传递对象时,运行startActivity(intent)出错,程序直接闪退,因此改成这样使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android ,你可以通过以下步骤在代码动态调用自定义属性: 1. 首先,在 res/values/attrs.xml 文件定义自定义属性。例如,我们定义一个名为 customMargin 的自定义属性: ```xml <resources> <declare-styleable name="CustomView"> <attr name="customMargin" format="dimension" /> </declare-styleable> </resources> ``` 2. 在你的自定义视图类中获取和使用自定义属性的值。例如,我们在 CustomView 类中获取 customMargin 的值并应用到视图上: ```java public class CustomView extends View { private int customMargin; public CustomView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomView); customMargin = typedArray.getDimensionPixelSize(R.styleable.CustomView_customMargin, 0); typedArray.recycle(); // 在这里可以根据 customMargin 的值做相应的操作,例如设置边距等 // ... } } ``` 在上述示例,我们通过 getContext().obtainStyledAttributes(attrs, R.styleable.CustomView) 方法获取 TypedArray 对象,然后使用 getDimensionPixelSize 方法获取 customMargin 属性的值。 3. 在 XML 布局文件使用自定义视图,并设置自定义属性的值。例如: ```xml <com.example.CustomView android:layout_width="match_parent" android:layout_height="wrap_content" app:customMargin="16dp" /> ``` 在上述示例,我们使用 app:customMargin="16dp" 来设置 customMargin 的值为 16dp。 通过以上步骤,你可以在代码动态调用自定义属性,并根据其值做相应的操作。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值