先來看一下Android的文件上怎麼說明的
android:freezesText
If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. By default this is disabled; it can be useful when the contents of a text view is not stored in a persistent place such as a content provider. For
EditText
it is always enabled, regardless of the value of the attribute.
May be a boolean value, such as "
true
" or "false
".預設這個設定是關閉的,當你開啟時,它會完整保留TextView上的內容,遊標位置除外。
在EditText中,這個設定總是開啟的。
預設情況下,當我們用在執行過程中,透過程式去設定TextView內容後,當螢幕進行旋轉後,
TextView的內容會消失.
以下是範例程式碼,當按下Add Button後,會把TextView的內容+1
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView textView=(TextView)findViewById(R.id.txt); Button button=(Button)findViewById(R.id.add); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int num=0; if (!textView.getText().toString().equals("")) { num=Integer.parseInt(textView.getText().toString()); } num++; textView.setText(String.valueOf(num)); } }); }
例如我按了六下Button,目前TextView的內容是6
當我進行螢幕旋轉後,TextView的內容不見囉
如果我將freezesText設為True
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.boywhychen.context_menu.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/txt" android:freezesText="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/add" android:text="Add" android:layout_below="@+id/txt" /> </RelativeLayout>
執行結果如下
它會保留TextView的內容。
參考資料:
https://developer.android.com/reference/android/widget/TextView.html
沒有留言:
張貼留言