0

首先,对不起我的英语不好。我正在开发交互式应用程序,它可以从另一个应用程序更新应用程序中的视图(UI)。你能告诉我如何将视图/布局从一个应用程序共享到另一个应用程序吗?请任何建议。谢谢 !!!

4

1 回答 1

0

我不明白你到底想做什么,我假设你想在点击 App A 中的按钮后启动 App B 并给 App B 一些信息。这样做对 Intents 没有问题。我真的不知道您要发送什么样的数据,但由于看起来数据有点复杂,我将在此示例中发送一个可序列化的对象,但您几乎可以发送任何类型的数据。有关更详细的文档,请参阅 Android 意图指南:http: //developer.android.com/reference/android/content/Intent.html

首先,您要发送的对象需要实现 Serializable:

public class DataContainer implements Serializable {
     ...
}

这是启动 App B 的 App A 的 OnClickListener:

button.setOnClickListener(new View.OnClickListener() {

     @Override
     public void onClick(View view) {
        Context context = getApplicationContext();

        // The Object you are trying to send
        DataContainer container = getData(); 

        // Create the Intent to start the other App
        Uri webpage = Uri.parse("http://www.android.com");
        Intent intent = new Intent(Intent.ACTION_VIEW, webpage);

        // Add the object to the Intent. With the String "Data" you can later retrieve the Object in the other App
        intent.putExtra("Data", container);

        // Start the other App
        context.startActivity(intent);
     }   
});

在应用 B 的主 Activity 中的 onCreate 方法中,您可以检索对象:

@Override
protected void onCreate (Bundle savedInstanceState) {

    // This means you only retrieve the data on the first start of the App, not after an orientation change etc.
    if(savedInstanceState == null) {

        // Get the Intent the App was started with.
        Intent intent = getIntent();

        // Retrieve the Object you wanted to send to this App.
        DataContainer data = (DataContainer) intent.getSerializableExtra("Data");
    }
}

在本例中,我使用字符串“Data”作为标签将对象附加到 Intent。永远不要在真正的应用程序中硬编码这样的字符串。您应该为此目的定义一个常量。

编辑:

如果您想发送布局,我只需发送资源 ID,如下所示:

在应用程序 A 中:

int resId = R.layout.layout_to_send;
intent.putExtra("layout", resId);

在应用 B 中:

int resId = intent.getIntExtra("layout", -1);
...
if(resId >= 0) {
    View view = layoutInflater.inflate(resId, parent, false);
    ...
}

无论如何,我不建议这样做。如果您执行此类操作,您会将信息发送到与该应用程序无关的另一个应用程序,这些应用程序在设计上应该相互独立。考虑一下这样的事情:

创建一个包含其他应用程序应该执行的所有可能操作的枚举。

public enum Action {
    SHOW_VIEW_A,
    SHOW_VIEW_B,
    ...
}

将其添加到 App A 中的意图中:

intent.putExtra("action", Action.SHOW_VIEW_A);

在 App B 中,对每个可能的情况做出反应。

Action action = intent.getSerializableExtra("action");

View view = null;
switch(action) {
    case SHOW_VIEW_A:
        view = layoutInflater.inflate(R.layout.view_a, parent, false);
        break;

    case SHOW_VIEW_B:
        view = layoutInflater.inflate(R.layout.view_b, parent, false);
        break;

    default:
        break;
}

if(view != null) {
    ...
}
于 2013-11-04T05:25:09.453 回答