标签:intent print 获取资源id end create str 获取 main log
解决如下:由于打包出来的jar只有源代码的.class 文件,不包含资源文件,我们就把jar包中用到的资源放到你使用该jar的工程里面。然后通过反射即可,这里给出反射类:
public class MResource {
public static int getIdByName(Context context, String className, String resName) {
String packageName = context.getPackageName();
int id = 0;
try {
Class r = Class.forName(packageName + ".R");
Class[] classes = r.getClasses();
Class desireClass = null;
for (Class cls : classes) {
if (cls.getName().split("\\$")[1].equals(className)) {
desireClass = cls;
break;
}
}
if (desireClass != null) {
id = desireClass.getField(resName).getInt(desireClass);
}
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
}
这里演示项目中打开jar中的activity的实例
这里给出jar中activity的代码:
public class JarActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(MResource.getIdByName(this, "layout", "jar_layout"));
ImageView mPlayerLogo = (ImageView) this.findViewById(MResource.getIdByName(this,
"id", "logo"));
mPlayerLogo.setImageResource(MResource.getIdByName(this, "drawable", "ic_launcher"));
}
}
**这里:利用反射根据资源名字获取资源ID加载布局+设置图片
在项目中打开jar的JarActivity的实现代码如下:
注:由于jar没有布局文件和资源文件,所以需要把布局(jar_layout)copy到项目中,aar则不需要**
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_jar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClassName(getApplication(), "com.zhh.librarydemo.JarActivity");
startActivity(intent);
}
});
}
}
jar_layout布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
在清单文件中注册:
<activity android:name="com.zhh.librarydemo.JarActivity"/>
标签:intent print 获取资源id end create str 获取 main log
原文地址:http://blog.51cto.com/1206995290qq/2331970