2017-09-10 256 views
-2

我想共享4個不同片段之間的字符串值。 如果我在一個片段中改變一個值,我想把這個值發送給其他片段。不同片段之間共享數據

我該怎麼做?

我唯一知道的是,在一個片段,我可以改變像

String newValue = "New Text"; 
View v = inflater.inflate(R.layout.fragment_one, container, false); 
Textview tv = (Textview) v.findViewById(R.id.textview_from_fragment_one); 
tv.setText(newValue); 

一個TextView但我怎麼能發送NEWVALUE例如片段fragment_two和fragment_three?

+0

初學者,我會建議你看看事件總線 - https://github.com/greenrobot/EventBus 你可以看看如何整合它的例子/教程 – chornge

+1

使用接口https://developer.android.com /training/basics/fragments/communicating.html –

+0

在問這個問題之前,您是否做過任何搜索? – meh

回答

2

我建議你使用EventBus庫,here是的教程如何開始使用EventBus。

你也可以用RxJava與this教程做到這一點。

但是,如果你不想用那麼任何庫:

  1. 首先創建一個界面如下圖所示:

    public interface Data { 
    
        void dataChanged(String changedString); 
    
    } 
    
  2. 實現你所有的碎片像的這個接口這個:

    public class FirstFragment extends Fragment implements Data { 
    
        ... 
    
        @Override 
        public void dataChanged(String changedString){ 
    
         // In this method you'll receive the changed string value 
    
        } 
    
    } 
    
  3. 在你的活動中創建一個方法l IKE如下:

    public void changeData(String changedData){ 
    
        // Notify your first fragment 
        Data data = myFirstFragment; 
        data.dataChanged(changedData); 
    
        // Notify your second fragment 
        data = mySecondFragment; 
        data.dataChanged(changedData); 
    
        // Other fragments 
        ... 
    
    } 
    
  4. ,只要你改變了字符串值,通知其他片段是這樣的:

    // Call this inside your fragment 
    ((YourActivity)getActivity()).changeData(CHANGED_VALUE); 
    
0

您可以使用Bundle

String newValue = "New Text"; 

Bundle bundle = new Bundle(); 
// you can put as much fragments as you want 

NewFragment fragment = new NewFragment(); 
SecondFragment fragment_two = new SecondFragment(); 
ThirdFragment fragment_three = new ThirdFragment(); 

bundle.putString("some_tag", newValue); 
fragment.setArguments(bundle); 
fragment_two.setArguments(bundle); 
fragment_three.setArguments(bundle); 

在任何設置有這個值添加此片段:

if (bundle != null) 
{ 
    String newValue = getArguments().getString("some_tag"); 
} 
0

您可以使用捆綁,如(把在開始活動額外)的片段:

  1. 當通話片段活動:

    0在活動中使用的接口呼叫梅索德用於替換片段:
    Fragment fragment = new ExampleFragment(); 
    
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
    
    Bundle bundle = new Bundle(); 
    bundle.putString("key", "TEST"); 
    fragment.setArguments(bundle); 
    
    transaction.replace(R.id.frame , fragment); 
    transaction.commit(); 
    
  2. 在片段onViewCreated()將這個:

    String exampleString; 
    Bundle bundle = this.getArguments(); 
        if (bundle != null) { 
        exampleString = bundle.getString("key", ""); 
    
        Toast.makeText(getActivity() , exampleString , Toast.LENGTH_SHORT).show(); 
    

注意。