2016-10-27 74 views
0

可否通過告訴我從活動移動到片段的最佳方式來協助您?這是我迄今爲止,但它似乎並沒有工作。 這是怎麼了調用該函數(的getCategory)如何在Android中從活動移動到片段?

private void selectItem(int group, int usage) 
    { 
     if (!shown) return; 
     classificationGroup = group; 

     ((DashboardActivity)getActivity()).getCallCategory(classificationGroup); 
    } 

而且在活動中,我試圖移動到一個片段

public Fragment getCallCategory(int position) { 


     return new CallLogsFragment(); 
    } 
+1

你是什麼意思?你怎麼調用這個函數? – Piyush

+0

@Puyish我編輯了這個問題 – Zidane

回答

0

的標準模式創建片段看起來是這樣的:

在你的片段類中(確保導入android.support.v4.app.Fragment):

public class MyFragment extends Fragment { 

    public static final String TAG = "MyFragment"; 

    private int position; 

    // You can add other parameters here 
    public static MyFragment newInstance(int position) { 
     Bundle args = new Bundle(); 
     // Pass all the parameters to your bundle 
     args.putInt("pos", position); 
     MyFragment fragment = new MyFragment(); 
     fragment.setArguments(args); 
     return fragment; 
    } 


    @Override 
    public void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     this.position = getArguments().getInt("pos"); 
    } 
} 

您的活動內幕:

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     // Add your parameters 
     MyFragment fragment = MyFragment.newInstance(10); 
     // R.id.container - the id of a view that will hold your fragment; usually a FrameLayout 
     getSupportFragmentManager().beginTransaction() 
      .add(R.id.container, fragment, MyFragment.TAG) 
      .commit(); 
    } 
} 

當你要訪問您的片段實例的公共方法,使用FragmentManager#findFragmentByTag(字符串標籤)找到你的片段的實例:

MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(MyFragment.TAG); 
    if(fragment != null){ 
     // Do something with fragment 
    } 

對於更詳細的解釋,我建議你閱讀關於碎片的官方文檔:https://developer.android.com/guide/components/fragments.html