1

後空我在ListFragment調用getListView()OnActivityCreated()。它工作正常,但如果我旋轉設備屏幕並再次調用getListView(),它將返回null。ListFragment getListView()返回屏幕旋轉

這是ListFragment 代碼:

public class MyListFragment extends ListFragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.my_list_fragment, container, false); 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     ListView list = getListView(); 

     if (list != null) { 
      //List is not null! 
     } 
     else { 
      //List is null, there is an error. 
     } 
    } 

} 

這是佈局的xml(my_list_fragment.xml):

<ListView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/list" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

回答

5

我想你應該把它在onViewCreated():

@Override 
public void onViewCreated(View view, Bundle savedInstanceState) { 
    super.onViewCreated(view, savedInstanceState); 
    ListView list = getListView(); 

    ... 
} 
+0

在屏幕旋轉之前,它返回ListView,但返回null之後。 –

+0

你試過這個嗎?:ListView list = getView()。findViewById(R.id.list); –

+0

非常感謝,但它返回NULL(旋轉屏幕後)。 –

1

,這是我的解決方案:

在我ListFragment我推翻了的onCreate方法是這樣的...

@Override 
public void onCreate(Bundle savedState) { 
    super.onCreate(savedState); 
    setRetainInstance(true); // handle rotations gracefully 

    ... 
} 

在我FragmentActivity我在中加了標籤的FragmentManageronCreate這樣的方法...

@Override 
public void onCreate(Bundle savedState) { 
    super.onCreate(savedState); 

    ... 

    // create or retrieve the venue list fragment 
    final String venueListTag = VenueListFragment.class.getName(); 
    final FragmentManager fragmentManager = getSupportFragmentManager(); 
    VenueListFragment venueListFragment = (VenueListFragment) fragmentManager.findFragmentByTag(venueListTag); 
    if (venueListFragment == null) { 
     venueListFragment = new VenueListFragment(); 
     final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
     fragmentTransaction.replace(R.id.main, venueListFragment, venueListTag); 
     fragmentTransaction.commit(); 
    } 

    ... 
} 

here更多關於setRetainInstance如果您有興趣。 我不確定如果Android團隊不喜歡使用setRetainInstance但他們肯定會保守祕密