2012-12-01 21 views
0

海我是新來的這個在Android的碎片開發。我的問題是片段之間的導航。我在片段1中有一個按鈕,在片段2中有一個文本視圖,並且我有活動activity1,我在xml中聲明瞭這兩個片段。我的問題是,當我按下fragment1中的按鈕時,它必須攜帶一些文本並在fragment2的textview中顯示,然後才必須檢查fragment2是否在相同佈局中?在android中的碎片導航

代碼對我很有幫助。在此先感謝..........

+0

爲什麼你不會只使用Google?這個主題有很多教程。 – Egor

+0

你能否給我提供一些鏈接? –

回答

0

首先宣佈你吹氣成onCreateView(在2ndFragmentClass)象下面這樣:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_content, container, false); 

    return view; 
} 

請考慮fragment_content必須在租賃有其自身內部一個TextView(以便我們在片段內設置它的值)。然後,我們必須從第一個片段中更改此文本的值。所以,我們我們的第二個片段(包含TextView的片段)內像下面添加此構造函數:

public void setText(String name) { 
    TextView txt= (TextView) getView().findViewById(R.id.textView1); 
    txt.setNewText(name); 
    } 

簡單地說,它會像下面:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_content, container, false); 

    return view; 
} 
public void setText(String name) { 
    TextView txt= (TextView) getView().findViewById(R.id.textView1); 
    txt.setNewText(name); 
    } 

然後我們必須定義文本必須設置成2ndFragment from 1stFragmentClass。然後我們通過按下第一個片段中的按鈕來設置第二個片段的文本,如下所示:

@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 
    String url = "Hello, This is the text from 1st Fragment:)"; 
     //Here we try to declare 2nd fragment. 
    2ndFragmentClass fragment = (2ndFragmentClass) getFragmentManager() 
      .findFragmentById(R.id.detailFragment); 
     fragment.setNewText(url); 
} 
+0

如果您覺得它有用,請將其標記爲真實答案。 –