2013-01-22 37 views
0

我原以爲這很容易,但它比我想象的更困難。我只想確定兩個片段何時在我的片段中的一個屏幕上可見。我不確定onCreate是否是最好的地方,但我試過onResume,onActivityCreated,onResume,onCreateViewonAttach。我認爲這些片段實際上並不是可見的,直到後來才知道,但不確定。確定兩個碎片何時可見

這是我想要使用的代碼:

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout 
    android:orientation="horizontal" 
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent" 
> 
    <fragment android:name="com.app.Fragment1" 
      android:id="@+id/fragment1" 
      android:layout_weight="1" 
      android:layout_width="0dp" 
      android:layout_height="fill_parent" 
    /> 

    <fragment android:name="com.app.Fragment2" 
      android:id="@+id/fragment2" 
      android:layout_width="0dp" 
      android:layout_weight="2" 
      android:layout_height="fill_parent" 
    /> 
</LinearLayout> 

public class Fragment2 extends SherlockListFragment 
{ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 

     setHasOptionsMenu(true); 

     final Fragment1 f1 = (Fragment1)getFragmentManager().findFragmentById(R.id.fragment1); 
     final Fragment2 f2 = (Fragment2)getFragmentManager().findFragmentById(R.id.fragment2); 

     Boolean isVisible = (f1 != null && f1.isVisible() && f2 != null && f2.isVisible()); 
    }  
} 

回答

0

onStart()是當片段是對用戶可見的,所以我建議把在onResumeisVisible代碼只是爲了安全起見。

+0

我通過使用'isAdded'而不是'isVisible'來得到它的工作。感謝您的迴應。 –

+0

啊,好了一個片段被添加到生命週期的不同方法中,但我很高興你能夠正常工作! – hwrdprkns