【问题标题】:Getting customview from another application at runtime在运行时从另一个应用程序获取自定义视图
【发布时间】:2012-01-05 05:36:30
【问题描述】:

我正在为从另一个应用程序获取CustomView 的想法而苦苦挣扎。假设我有两个应用程序 A 和 B。我知道包名称为 CustomView,例如 com.applicationb.CustomView。是否可以在运行时在应用程序A中创建该类的对象?

我的目标是找到一种方法来创建 CustomViews 并能够在我的应用程序中显示它们。但我希望它们(视图)是一个单独的 apk,可以发布到 Android Market,并作为某种扩展下载。

CustomView 只会在屏幕上显示某种动画(例如落叶)。它不适用于第一个应用程序中的任何数据。

编辑

我发现了这样的东西:

@SuppressWarnings("rawtypes")
Class c = Class.forName(package_name);
Method m = c.getDeclaredMethod(method_name);
m.setAccessible(true);
Canvas can= (Canvas) m.invoke(null, null); // since there are no parameters, and called function is static

我希望这会奏效。我让你知道。

【问题讨论】:

  • 不,您无法访问“视图”,但您可以使用 startActivity(Intent intent) 启动包含在另一个应用程序中的 Activity。这是相当基本的东西 - 我建议你阅读应用基础 - developer.android.com/guide/topics/fundamentals.html
  • 我不想使用其他包中的任何活动或服务。我只想使用一个函数,例如 getCanvas(),它将画布返回给我的应用程序。这背后的想法是其他开发人员可以在绘图画布后面制作自己的代码,我会在我的应用程序活动中绘制它。
  • 你为什么不用安卓库?

标签: android class import runtime custom-view


【解决方案1】:

我在这里承诺的是结果。

String packageName = "com.exapmle.sth";
String className = "com.exapmle.sth.CustomView";

String apkName = getPackageManager().getApplicationInfo(
    packageName, 0).sourceDir;
PathClassLoader myClassLoader = new dalvik.system.PathClassLoader(
    apkName, ClassLoader.getSystemClassLoader());
Class<?> handler = Class.forName(className, true, myClassLoader);
Constructor[] m = handler.getConstructors();
for (int i = 0; i < m.length; i++) {
    if (m[i].getName().contains("CustomView")) {
        animation = (View)m[i].newInstance(new Object[] { this });
        rootRL.addView(animation, new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.FILL_PARENT,
            RelativeLayout.LayoutParams.FILL_PARENT));
    }
}

使用此代码,可以使用应用程序 A 从应用程序 B 获取视图。

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2017-06-27
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    相关资源
    最近更新 更多