我在Tabbed Activity中有一个片段,当单击一个按钮时会创建新视图,问题是当创建视图并使用不同的信息填充信息时,我会滑动到另一个片段然后返回现在,使用按钮单击创建的所有视图都包含相同的信息。
在片段中:
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(view == null) {
view = inflater.inflate(R.layout.fragment_create_history, container, false);
}
Button addHistoryButton = (Button) view.findViewById(R.id.buttonAddHistory);
inflaterM = LayoutInflater.from(view.getContext());
root = (LinearLayout) view.findViewById(R.id.linearLayoutHistory);
mListener.onFragmentHistoryInteractionLoad();
addHistoryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View child = inflater.inflate(R.layout.list_history_layout, null);
child.setId(View.generateViewId());
root.addView(child);
}
});
return view;
}
R.layout.list_history_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_marginTop="5dp"
android:id="@+id/linearLayoutHistory">
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextStory"
android:hint="Story"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextYearRecorded"
android:hint="Year Recorded"
android:inputType="date"
/>
</LinearLayout>
答案 0 :(得分:0)
您需要在片段上创建可在视图上发生更改时设置的属性,例如:
private boolean mHistoryButtonAdded;
...
@Override
public void onClick(View v) {
View child = inflater.inflate(R.layout.list_history_layout, null);
child.setId(View.generateViewId());
root.addView(child);
mHistoryButtonAdded = true;
}
接下来,您需要覆盖onSaveInstanceState()
以保留这些属性,例如:
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("history-button-added", mHistoryButtonAdded);
super.onSaveInstanceState(outState);
然后,在onCreateView()
中,您将检查这些属性并从其状态重新创建视图,例如:
if (savedInstanceState != null) {
mHistoryButtonAdded = savedInstanceState.getBoolean("history-button-added", false);
if (mHistoryButtonAdded) {
View child = inflater.inflate(R.layout.list_history_layout, null);
child.setId(View.generateViewId());
root.addView(child);
}
}
另外请确保使用FragmentStatePagerAdapter
,这将保存并恢复状态。