2017-08-19 37 views
1

呼兒片段方法的適配器的功能:如何我有什麼結構從其活動中的Android

  1. 我有一個活動叫MainActivity.java
  2. 裏面MainActivity.javaParentFragment.java
  3. 現在ParentFragment.java裏面有ChildFragment.Java
  4. 現在ChildFragment.Java裏面有一個適配器 ChildAdapter.java
  5. 裏面ChildAdapter.java的是一個叫MyMethod()

現在,如何通過它的標籤訪問MyMethod()MainActivity.java

回答

1

下面是解

1.Find ParentFragmentMainActivity方法

2.And從ParentFragemnt實例使用getChildSupportManager()

3.And現在ChildFragment創建ChildAdapter可變全球並予以公佈

4.And從ChildFragment實例訪問發現ChildFragment對標籤的ChildAdapter

5.比你可以訪問MyMethod()ChildAdapter變量

1

我通常在Activity中使用這個方法,它必須替換Fragments:

/** 
* This method is used to load the fragment once an item gets selected 
* 
* @param fragment This is the chosen fragment you want to select 
*/ 
public void loadFragmentActivityFrameLayout(final Fragment fragment) { 

    // create a transaction for transition here 
    final FragmentTransaction transaction = getSupportFragmentManager() 
      .beginTransaction(); 

    // put the fragment in place 
    transaction.replace(
      R.id.frameLayoutId, 
      fragment, 
      fragment.getClass().getSimpleName()); 

    // this is the part that will cause a fragment to be added to back stack, 
    // this way we can return to it at any time using this tag 
     if(fragment instanceof Fragment1){ 
      transaction.addToBackStack(Fragmen1.class.getSimpleName()); 
     }else if(fragment instanceof Fragment2){ 
      transaction.addToBackStack(Fragment2.class.getSimpleName()); 
     }else if(fragment instance of Fragment3){ 
      transaction.addToBackStack(Fragment3.class.getSimpleName()); 
     }else if(fragment instanceof Fragment4){ 
      transaction.addToBackStack(Fragment4.class.getSimpleName()); 
     } 

    transaction.commit(); 
} 

然後你就可以在該活動檢索每個片段的情況下,像這樣:

Fragment1 frag1 = 
      (Fragment1)getSupportFragmentManager() 
        .findFragmentByTag(Fragment1.class.getSimpleName()); 

Fragment2 frag2 = 
      (Fragment2)getSupportFragmentManager() 
        .findFragmentByTag(Fragment2.class.getSimpleName()); 

Fragment3 frag3 = 
      (Fragment3)getSupportFragmentManager() 
        .findFragmentByTag(Fragment3.class.getSimpleName()); 

Fragment4 frag4 = 
      (Fragment4)getSupportFragmentManager() 
        .findFragmentByTag(Fragment4.class.getSimpleName()); 

然後,因爲你有一個適配器,使其在片段公開,讓我們說「 frag1" 不要忘記做‘的MyMethod()’的公共插入適配器

public CustomAdapter adapter; 

終於可以從活動獲取任何適配器方法:

frag1.adapter.MyMethod(); 

希望我已經清楚。

相關問題