2016-06-27 64 views
1

我在viewpager中有兩個選項卡。因此,在fragment1中,我輸入了一個文本,當選擇了tab2時,fragment2將從fragment1中的文本中獲取數據。我打開tab1 - >我輸入文本是「abcd」 - >我打開tab2 - >我想從tab1(fragment1)得到一個文本是「abcd」。如何在Xamarin Android上的標籤之間傳遞數據?

public class Fragment1 : Android.Support.V4.App.Fragment 
{ 
    Fragment2 frag2 = new Fragment2(); 
    public override void OnCreate(Bundle savedInstanceState) 
    { 
     base.OnCreate(savedInstanceState); 

     // Create your fragment here 
    } 

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     // Use this to return your custom view for this Fragment 
     // return inflater.Inflate(Resource.Layout.YourFragment, container, false); 

     Singleton singleton = Singleton.GetInstance();; 
     singleton.SetSource("abcd"); 

    } 

}public class Singleton 
    { 
     private static Singleton singleton; 

     string a = null; 
     private Singleton() 
     { 

     } 

     public static Singleton GetInstance() 
     { 
      if (singleton == null) 
       singleton = new Singleton(); 
      return singleton; 
     } 
     public void SetSource(string text) 
     { 
      this.a = text; 
     } 

     public string showMessage() 
     { 
      return a; 
     } 


    } 
public class Fragment2 : Android.Support.V4.App.Fragment 
{ 
    public List<string> data = new List<string>(); 
    public void add(string t) 
    { 
     data.Add(t); 
    } 
    TextView txt; 
    public override void OnCreate(Bundle savedInstanceState) 
    { 
     base.OnCreate(savedInstanceState); 

     // Create your fragment here 


    } 

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     // Use this to return your custom view for this Fragment 
     // return inflater.Inflate(Resource.Layout.YourFragment, container, false); 

     //return base.OnCreateView(inflater, container, savedInstanceState); 
     return inflater.Inflate(Resource.Layout.view2, container, false); 
     txt = View.FindViewById<TextView>(Resource.Id.txtgetdata); 
     if (data != null) 
     { 
      txt.Text = data[0]; 
     } 
     else 
      Toast.MakeText(Application.Context, "no", ToastLength.Long).Show(); 

    } 
} 

我已經嘗試過了,但不具有的結果。

+0

肯定。其得到空 –

回答

0
Fragment fragment = new Fragment(); 
Bundle bundle = new Bundle(); 
bundle.putInt(key, value); 
fragment.SetArguments(bundle); 

在創建另一個片段

Bundle bundle = this.GetArguments(); 
int myInt = bundle.GetInt(key, defaultValue); 

optionaly兩個片段決不應直接溝通,應該通過活動

開發商的網站通信:

你經常會想要一個片段與另一個片段進行通信,例如要更改 示例基於用戶事件的內容。全部 片段與片段之間的通信通過關聯的 活動完成。兩個碎片不應該直接通信。

參考thisthis

+0

沒有結果 –

+0

沒有得到你可以詳細說明嗎? –

+0

'Bundle bundle = this.Arguments; txtv.Text = bundle.GetString(「key」);'。 this.Arguments爲空 –

相關問題