2013-11-04 33 views
0

第一個,對不起,我的英語不好。我正在開發交互式應用程序,可以從另一個應用程序更新應用程序中的視圖(UI)。 你能告訴我如何從一個應用程序共享視圖/佈局到另一個應用程序? 請有任何建議。 謝謝!在應用程序之間共享視圖

+0

請解釋一下您的要求 –

+0

例如:我有兩個應用程序:A和B.我點擊應用程序A上的按鈕,它向B發送廣播,B說更新視圖(取決於數據A發送B)。現在我使用json進行傳輸,但時間太長,而且不清楚。其他方式 ? – user1573559

+0

好吧,如果我瞭解您的要求,您的應用程序在您的設備上運行,並且當您單擊應用程序中的任何按鈕時,您希望應用程序b啓動不是它,因爲即使您將任何應用程序更新到應用程序b,它也不會在應用b啓動之前可見? –

回答

0

我不明白你想要做什麼,我假設你想在應用程序A中的按鈕被點擊並給予應用程序B一些信息之後啓動應用程序B.這樣做對Intents來說沒有問題。我真的不知道你想發送什麼樣的數據,但是因爲看起來數據有點複雜,我會在這個例子中發送一個可序列化的對象,但是你可以發送幾乎任何類型的數據。如需更詳細的文檔,請參閱Android的指引意圖:你想 http://developer.android.com/reference/android/content/Intent.html

首先,對象發送需要實現Serializable:

public class DataContainer implements Serializable { 
    ... 
} 

下面是從應用程序A中的OnClickListener這將啓動應用程序B:

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的在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"); 
    } 
} 

在此示例中,我使用字符串「數據」作爲標籤將對象附加到意圖。切勿在實際應用程序中硬編碼這樣的字符串。你應該爲此目的定義一個常量。

編輯:

如果你想送一個佈局,我只想送的ressource ID,像這樣:

在應用答:

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, 
    ... 
} 

它添加到意圖在應用程式:

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

在應用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) { 
    ... 
} 
+0

鍶,我沒有解釋清楚我的問題。我可以發送佈局嗎? – user1573559

+0

嗯,是的,如果應用B已經包含佈局,您只需發送資源ID。我將相應地編輯我的問題。 –

+0

非常感謝。我會試試你的方式。並讓你知道結果。 – user1573559

相關問題