2016-04-04 13 views
1

私はその親アクティビティからフラグメントメソッドを呼び出したいと思います。そのために私はフラグメントのオブジェクトが欲しい。findFragmentByTagはandroidでnullを返します

親アクティビティは、次のようでframeLayoutでフラグメントを持っている:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/bottom_buttons" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 

これは、フラグメントオブジェクトを取得するためのコードです。

FragmentBottomButtons fragment = new FragmentBottomButtons(); 
     FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
     ft.replace(R.id.bottom_buttons, fragment,"FragmentTag"); 
     //ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
     //ft.addToBackStack(""); 
     ft.commit(); 


     /* 
     getSupportFragmentManager() 
       .beginTransaction() 
       .add(R.id.bottom_buttons, new FragmentBottomButtons()) 
       .commit(); 

     */ 
     frag = (FragmentBottomButtons) getSupportFragmentManager().findFragmentByTag("FragmentTag"); 
     //fragmentBottomButtons = (FrameLayout)findViewById(R.id.bottom_buttons); 
     if (frag == null){ 
      Utility.displayToast("fragmnt is null"); 
     } 

しかしnullを返しています。

誰でも私にこれを助けることができますか?何がここに間違っていますか?

+1

は(fragmentManager.executePendingTransactionsを実行してください)。フラグメントが得られる前に、それが動作するかどうかを確認してください。 commit()は非同期に動作し、アクションが完全に完了する前に呼び出すことができます。 – aminner

答えて

5

commit()メソッドを使用している場合、誰もあなたのフラグメントがFragmentManagerにその場でアタッチされないことを保証します。

FragmentManagerのロジックが原因で発生します。\ replace \を追加すると、フラグメントが削除され、FragmentTransactionが作成され、FragmentManager内の実行キューに挿入されます。実際には、FragmentManagerがタスクをエンキューするまで待っているすべてのトランザクション。あなたはこの方法では、保留中のトランザクションを開始し、使用findFragmentById()方法のために、より硬いことを確認してください

getSupportFragmentManager().executePendingTranscation(); 

を経由してフラグメントの下にエンキュー各タスクを強制することができ、このような状況を回避するために

だから、最終的には次のものが必要です。

CustomFragment fragment = new CustomFragment(); 
FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
//add or replace or remove fragment 
ft.commit(); 

getSupportFragmentManager().executePendingTranscation(); 

CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("FragmentTag"); 
0

Fragmentはまだ添付されていません。後でfindFragmentByTag()に電話する必要があります。例として、リスナーをFragmentに追加し、メソッドでActivityに電話をして、にFragmentが作成されたことを伝えることができます。

関連する問題