2012-03-20 10 views
4

アンドロイドが提供している互換性ライブラリandroid.cupport-v4.jarを使用していました。問題が見つかったため、タブにいくつかのフラグメントが含まれていました。別のフラグメントが追加されたときにフラグメントアクティビティがnullになる

私は、次のコードを呼び出すアダプタ内のアイテムのリスナーから、GridViewコントロールを持って開始するタブがあります。

FragmentManager manager = getSupportFragmentManager(); 
FragmentTransaction ft = manager.beginTransaction(); 
ft.add(R.id.relativeLayoutContent, newFragment); 
//  ft.replace(R.id.relativeLayoutContent, newFragment); 
ft.addToBackStack(null); 
ft.commit(); 

私は新しいフラグメントを開いて、バックに行くときの問題があります最初の1つはonAttachのために行かない、それは決してde-attachされなかったので、そして新しいフラグメントがあったので、私は再び要素をクリックしようとすると、最初のものではなく最後のものを保持しているそれは、フラグメントからのgetActivityメソッドがnullであることを私に伝えます。

この問題を回避する方法はありますか?

答えて

0

私はあなたが達成しようとしていることは確かではありませんが、とにかくそれを刺すつもりです。

フラグメントマネージャを使用して異なるフラグメントを保持する必要がありますが、FragmentTransactionでaddメソッドを使用する場合は、フラグメントをタグに割り当てて、フラグメント間を簡単に切り替えることができます。

TabActivityも廃止予定です。 ActionBarのタブの使用について考えましたか?ここで http://developer.android.com/guide/topics/ui/actionbar.html#Tabs

私は、私が現在働いている何かから引き出さ抜粋です:

public void changeFragment(String tag){ 

    Fragment tmpFragment; 
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); 

    //look to see if we have already added the fragment 
    tmpFragment = getFragmentManager().findFragmentByTag(tag); 

    //we currently have a fragment, hide it 
    if (currentFragment != null){ 
     fragmentTransaction.detach(currentFragment); 
    } 

    //did not find the fragment 
    if (tmpFragment == null){ 
     if (tag.equals("map")){ 
     currentFragment = CustomMapFragment.newInstance(); 
     } else if (tag.equals("list")){ 
     currentFragment = ListFragment.newInstance(); 
     }else { 
     //TODO 
    } 
    //add fragment for 1st time 
    fragmentTransaction.add(R.id.content_frame, currentFragment, tag); 
    } else { 
    //we found the fragment 
    currentFragment = tmpFragment; 
    fragmentTransaction.attach(currentFragment); //show the fragment we found 
    } 
    fragmentTransaction.commit(); 
} 

あなたが自分のタグに基づいてフラグメントを切り替えるには、このメソッドを使用することができます。

関連する問題