圖片,佈局,string等)打進jar包
阿新 • • 發佈:2018-12-18
解決如下:由於打包出來的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"/>