从另一个APK动态加载资源(布局) [英] Load resource (layout) from another apk dynamically
问题描述
我设法拉布局,我把它添加到我的viewflipper,然而,其加载为空白。
I managed to pull the layouts, and i add it to my viewflipper, however, there it is loaded as blank.
在code是,
Resources packageResources;
Context packageContext;
try
{
packageResources = pm.getResourcesForApplication(packageName);
packageContext = this.createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE + Context.CONTEXT_IGNORE_SECURITY);
}
catch(NameNotFoundException excep)
{
// the package does not exist. move on to see if another exists.
}
Class layoutClass;
try
{
// using reflection to get the layout class inside the R class of the package
layoutClass = packageContext.getClassLoader().loadClass(packageName + ".R$layout");
}
catch (ClassNotFoundException excep1)
{
// Less chances that class won't be there.
}
for( Field layoutID : layoutClass.getFields() )
{
try
{
int id = layoutID.getInt(layoutClass);
XmlResourceParser xmlResourceLayout = packageResources.getLayout(id);
View v = new View(this, Xml.asAttributeSet(xmlResourceLayout));
this.viewFlipper.addView(v);
}
catch (Exception excep)
{
continue;
}
}
我没有得到任何错误,我调试和检查。布局ID是正确的。然而,在我viewFlipper它只是一片空白。无警告或错误,我可以找到。
I get no errors, and i debugged and checked. The layout IDs are correct. However, in my viewFlipper its just blank. No warnings or errors i can find.
推荐答案
终于得到它....它其实很简单!!!!
Finally got it.... Its actually simple !!!!
下面是我做的......
Here is what i did...
-
在目标APK,只有资源和布局,没有应用程序或活动code。我创建了一个类,
In the target apk, there is only resources and layouts with no application or activity code. I created a class,
public final class ViewExtractor
{
private static final int NUMBER_OF_LAYOUTS = 5;
public static View[] getAllViews(Context context)
{
View[] result = new View[ViewExtractor.NUMBER_OF_LAYOUTS];
result[0] = View.inflate(context, R.layout.layout_0, null);
result[1] = View.inflate(context, R.layout.layout_1, null);
result[2] = View.inflate(context, R.layout.layout_2, null);
result[3] = View.inflate(context, R.layout.layout_3, null);
result[4] = View.inflate(context, R.layout.layout_4, null);
return result;
}
}
然后在我当前的应用程序,我修改了早先code。的修改发生一次包已被证实存在。
Then in my current application, I modified my earlier code. The modification takes place once package has been verified to exist.
// If the package exists then get the resources within it.
// Use the method in the class to get the views.
Class<?> viewExtractor;
try
{
viewExtractor = packageContext.getClassLoader().loadClass(packageName + ".ViewExtractor");
}
catch (ClassNotFoundException excep)
{
continue;
}
View[] resultViews;
try
{
Method m = viewExtractor.getDeclaredMethod("getAllViews", Context.class);
resultViews= (View[])m.invoke(null, new Object[]{packageContext});
for( View v : resultViews)
{
this.viewFlipper.addView(v);
}
}
catch (Exception excep)
{
excep.printStackTrace();
}
这篇关于从另一个APK动态加载资源(布局)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!