我有一个包含两个片段的活动。该活动具有不同的纵向和横向布局,但片段保持不变(使用标签创建并重复使用)。在其中一个片段中,我有 xml 定义的 textview,它有 android:freezesText="true" 行,但在屏幕旋转后它仍然会丢失文本。为什么会发生这种情况?
片段的布局:
<?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:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="@+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/dip10"
android:freezesText="true"
android:gravity="center"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
片段的类:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayFrag extends Fragment {
@Override
public View
onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.display_frag, container, false);
TextView tvDisplay = (TextView) view.findViewById(R.id.tvDisplay);
tvDisplay.setText(getArguments().getString(Keys.NAME)
+ ", how are you? your phone number is " + getArguments().getString(Keys.PHONE));
return view;
}
}
活动:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragMan = getSupportFragmentManager();
InputFrag inputFrag = (InputFrag) fragMan.findFragmentByTag(Keys.TAG_INPUT_FRAG);
if (inputFrag == null) {
fragMan.beginTransaction().add(R.id.hook1, new InputFrag(), Keys.TAG_INPUT_FRAG)
.commit();
} else {
fragMan.beginTransaction().replace(R.id.hook1, inputFrag, Keys.TAG_INPUT_FRAG).commit();
}
}
public void submit(View view) {
FragmentManager fragMan = getSupportFragmentManager();
DisplayFrag displayFrag = (DisplayFrag) fragMan.findFragmentByTag(Keys.TAG_DISPLAY_FRAG);
if (displayFrag == null) {
displayFrag = new DisplayFrag();
displayFrag = putBundle(displayFrag);
fragMan.beginTransaction().add(R.id.hook2, displayFrag, Keys.TAG_DISPLAY_FRAG).commit();
} else {
fragMan.beginTransaction().replace(R.id.hook2, displayFrag, Keys.TAG_DISPLAY_FRAG)
.commit();
}
}
private DisplayFrag putBundle(DisplayFrag displayFrag) {
Bundle bundle = new Bundle();
bundle.putString(Keys.NAME, ((EditText) findViewById(R.id.etName)).getText().toString());
bundle.putString(Keys.PHONE, ((EditText) findViewById(R.id.etPhone)).getText().toString());
displayFrag.setArguments(bundle);
return displayFrag;
}
}
(提交响应另一个片段上的按钮,该按钮行为正确)。