我有一個簡單的HoloEverywhere與一個片段容器構建的活動。 ListFragment在開始時出現,並且正常顯示。然後,單擊列表項將ListFragment替換爲另一個片段,並將其添加到backstack中。但是當我按下按鈕時,列表是空的,雖然它恢復正常。有一些代碼:返回後ListFragment爲空
活動
public class MainActivity extends Activity implements SongsFragment.IActivityCallback {
public final static String TAG = "Lyrics";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "STarted.");
setContentView(R.layout.frags);
}
@Override
public void itemSelected(int id) {
Log.d(TAG, "itemSelected");
LyricsFragment lyrics = new LyricsFragment();
if(findViewById(R.id.frag_frame) != null) {
Bundle args = new Bundle();
args.putInt("id", id);
lyrics.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frag_frame, lyrics);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
斷枝佈局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frag_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:name="android.app.ListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.anth.lyrics.SongsFragment"
tools:layout="@layout/song_fragment" />
</FrameLayout>
LyricsFragment:
public class LyricsFragment extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.container = container;
View ret = inflater.inflate(R.layout.lyricsview, container, false);
return ret;
}
...
SongsFragment:
public class SongsFragment extends ListFragment {
private IActivityCallback callback;
private ArrayList<Song> songs;
final static String TAG = "SOng Fragment";
public interface IActivityCallback {
public void itemSelected(int id);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextView t_id = (TextView) v.findViewById(R.id.song_id);
int s_id = Integer.valueOf(t_id.getText().toString());
Log.d(TAG, "Select item");
callback.itemSelected(s_id);
super.onListItemClick(l, v, position, id);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callback = (IActivityCallback) getActivity();
DBRead db = new DBRead(getActivity());
songs = db.getLast(10);
db.close();
SongListAdapter adapt = new SongListAdapter(getActivity(), R.layout.songs_item, songs);
setListAdapter(adapt);
}
}
我已經測試了2.3.3和4.0.4上,結果是一樣的。那麼,如何使它正常工作?
它解決了我的問題,謝謝! – 2013-05-03 13:31:36
onResume()中的設置列表適配器是正確的把戲:) – Warpzit 2013-12-11 06:33:36
當我從新的片段中取出時,onResume()不會觸發。所以@ nbe_42解決方案似乎更好 – user2396640 2017-09-18 21:02:27