1
我想讓我的ListFragment返回到完全相同的位置,當我從別處返回它但它不工作。我的代碼中的listView
所有實例變成紅色,並返回以下錯誤:ListView不回到確切的滾動位置
無法解析符號「的ListView」
我真的不知道爲什麼會這樣,當我用ListView listView = getListView();
發生。我甚至嘗試以下這些網頁上的解決方案:
- FutureStudio.io - How to Save and Restore the Scroll Position and State of a Android ListView
- Stack Overflow - Eugene Mymrin's answer - Maintain/Save/Restore scroll position when returning to a ListView
我發現它很混亂遵循以人的建議,因爲他們確實有所不同。
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fragmentherbs">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
爪哇
public class FragmentHerbs extends ListFragment {
public FragmentHerbs() {
// Required empty constructor
}
public static FragmentHerbs newInstance() {
return new FragmentHerbs();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_herbs, container, false);
ListView listView = getListView();
initialize();
return view;
}
List<Herb> list = new ArrayList<>();
private void initialize() {
String[] items = getActivity().getResources().getStringArray(R.array.herb_names);
for (int n = 0; n < items.length; n++){
Herb herb = new Herb();
herb.setID();
herb.setName(items[n]);
list.add(herb);
}
HerbsListAdapter mAdapter = new HerbsListAdapter(list, getActivity());
setListAdapter(mAdapter);
}
@Override
public void onPause() {
// Save ListView state @ onPause
Log.d(TAG, "saving listview state @ onPause");
state = listView.onSaveInstanceState();
super.onPause();
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore previous state (including selected item index and scroll position)
if(state != null) {
Log.d(TAG, "trying to restore listview state..");
listView.onRestoreInstanceState(state);
}
}
}
添加的ListView ListView的作爲FragmentHerbs類變量和在onCreateView初始化它 - 的ListView = getListView(); – garmax1
@ garmax1請在格式設置中顯示您的建議 – MacaronLover