rf中resourceid_getResource.getIdentifier() 利用资源名称来获取ID

android中代码的实现与xml布局文件常常绑定在一起,可以通过getResouce.getIdentifier利用android资源文件名称来获取其ID,从而使代码的实现与xml的实现相分离。以下为封装类的实现:

import android.content.Context;

public class UtilTool {

public static final String ID = "id";

public static final String DRAWABLE ="drawable";

public static final String STRING ="string";

public static final String LAYOUT ="layout";

public static final String XML ="xml";

public static int

getResIdentifier(Context context, String name, String type)

{

return

context.getResources().getIdentifier(name, type,

context.getPackageName());

}

public static int

getId(Context context, String name) {

return getResIdentifier(context, name,

ID);

}

public static int

getDrawable(Context context, String name) {

return getResIdentifier(context, name,

DRAWABLE);

}

public static int

getString(Context context, String name) {

return getResIdentifier(context, name,

STRING);

}

public static int

getLayout(Context context, String name) {

return getResIdentifier(context, name,

LAYOUT);

}

public static int

getXml(Context context,String name){

return

getResIdentifier(context,name,XML);

}

}

在Activity中的调用方法如下:

public class MainActivity extends Activity {

private static final String TAG = "MainActivity";

private Activity activity = null;

private LinearLayout linear_main = null;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Log.d(TAG,"-------------onCreate---------------");

setContentView(UtilTool.getLayout(getApplicationContext(),

"activity_main"));

linear_main =

(LinearLayout)findViewById(UtilTool.getId(getApplicationContext(),

"linear_main"));

startButton = (Button)

findViewById(UtilTool.getId(getApplicationContext(),

"login"));

}

}​

​其中,activity_main为对应的xml文件的文件名,linear_main为xml中对应的LinearLayout对象。

以上即实现代码的实现与xml的布局相分离,​通过getResouce.getIdentifier可实现资源文件名称来获取其ID,很好的实现面向对象的可维护性与可扩展性。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值