如何在协作开发安卓项目中打jar包给合作人

来源:互联网 发布:淘宝苏宁易购是正品吗 编辑:程序博客网 时间:2024/05/10 10:05

一般情况下,id都是安卓自动生成的。使用时只要用R.id.xx就可以了。但是,在合作开发安卓时,需要将自己开发的代码部分打成jar包,甚至做混淆。

这就需要使用java的反射机制。在取id时使用如下类,避免了硬编码。res文件只能乖乖的交给合作方了。当然可能还有更好的方法解决这个问题。

 

使用方法如:

 

  (ImageButton) findViewById(GetItemId.getIdResIDByName(this, "title_exit"));

 

 

import java.lang.reflect.Field;

import android.content.Context;
import android.util.Log;

public class GetItemId {

 public static int getItemId(Context paramContext, String paramString1,
   String paramString2) {
  try {
   Class<?> localClass = Class.forName(paramContext.getPackageName()
     + ".R$" + paramString1);
   Field localField = localClass.getField(paramString2);
   int i = Integer.parseInt(localField.get(localField.getName())
     .toString());
   return i;
  } catch (Exception localException) {
   Log.e("getIdByReflection error", localException.getMessage());
  }

  return 0;
 }

 public static int[] getItemIdArray(Context paramContext,
   String paramString1, String paramString2) {
  try {
   Class<?> localClass = Class.forName(paramContext.getPackageName()
     + ".R$" + paramString1);
   Field localField = localClass.getField(paramString2);
   int[] i = (int[]) localField.get(localField.getName().toString());
   return i;
  } catch (Exception localException) {
   Log.e("getIdByReflection error", localException.getMessage());
  }

  return null;
 }

 public static int getLayoutResIDByName(Context context, String name) {
  return context.getResources().getIdentifier(name, "layout",
    context.getPackageName());
 }

 public static int getIdResIDByName(Context context, String name) {
  return context.getResources().getIdentifier(name, "id",
    context.getPackageName());
 }

 public static int getStringResIDByName(Context context, String name) {
  return context.getResources().getIdentifier(name, "string",
    context.getPackageName());
 }

 public static int getDrawableResIDByName(Context context, String name) {
  return context.getResources().getIdentifier(name, "drawable",
    context.getPackageName());
 }
}

 

5 0
原创粉丝点击