Android: почему мой EditText сохраняет свое значение даже при изменении ориентации? - PullRequest
2 голосов
/ 02 декабря 2011

это вопрос из любопытства.

Недавно я только что узнал, что мне нужно заботиться о том, чтобы самому сохранять состояние своей активности при смене ориентации.

Но в одном из моих Макетов Edittext просто сохраняет свое значение, и я не понимаю, почему? Очевидно, я хотел бы воспроизвести это поведение для других EditTexts ...

Вот макет, текст редактирования - это android: id = "@ + id / createlistactivity_listname_edittext"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/title_bar"
        android:gravity="center"
        android:text="Enter a Name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/createlistactivity_listname_edittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:hint="Name..."
        android:singleLine="true" >

    </EditText>

</LinearLayout>


<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/CreateListActivity_HeaderLabel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/title_bar"
        android:gravity="center"
        android:text="Add Products to your new List"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:choiceMode="multipleChoice"
        android:footerDividersEnabled="true" >
    </ListView>

    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:text="No Products available. Insert some Products in the Products menu  first" />

</LinearLayout>


<LinearLayout
    android:orientation="horizontal"
    android:id="@+id/CreateListActivity_BottomBar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="2"
    style="@android:style/ButtonBar" >


    <ImageButton
        android:id="@+id/CreateListActivity_SaveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:onClick="saveButtonClicked"
        android:src="@drawable/tick_32" />


    <ImageButton
        android:id="@+id/CreateListActivity_CancelButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:onClick="cancelButtonClicked"
        android:src="@drawable/block_32_2" />

</LinearLayout>

</LinearLayout>

и вот создание для действия

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.createlistactivity_layout);

    _selectedItems = new HashMap<Integer, Integer>();
    _productDAO = new ProductDAO(getApplication());
    _listDAO = new ListDAO(getApplication());
    _productCursor = _productDAO.getAllProductsCursor();

    startManagingCursor(_productCursor);

    setUpListView();    

    final EditText listNameEditText = (EditText)this.findViewById(R.id.createlistactivity_listname_edittext);

    listNameEditText.setOnEditorActionListener(new OnEditorActionListener() {

        public boolean onEditorAction(TextView v, int actionId,
                KeyEvent event) {
            if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                in.hideSoftInputFromWindow(listNameEditText
                        .getApplicationWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return false;
        }
    });     
}

это код другого действия, содержащего текстовые правки, которые не сохраняют свое состояние

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >


<TableLayout
    android:id="@+id/TableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/productImage"
    android:background="@android:drawable/alert_light_frame" >

    <TableRow
        android:id="@+id/productview_toprow"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top" >

        <EditText
            android:id="@+id/productview_productname"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="Product Name"
            android:singleLine="true" >

            <requestFocus />
        </EditText>
    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_weight="1"
            android:gravity="center_vertical|center_horizontal"
            android:text="@string/productview_pricelabel"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@android:color/black" />

        <EditText
            android:id="@+id/productview_price_edittext"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="0.0"
            android:singleLine="true"
            android:inputType="numberDecimal" />
    </TableRow>

    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_vertical|center_horizontal"
            android:text="@string/productview_unitlabel"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@android:color/black" />

        <EditText
            android:id="@+id/productview_unit_edittext"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="kg|ml|..." />
    </TableRow>
</TableLayout>

и onCreate ...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.productview);

    _productName = (EditText)findViewById(R.id.productview_productname);
    _productPrice = (EditText)findViewById(R.id.productview_price_edittext);
    _productUnit = (EditText)findViewById(R.id.productview_unit_edittext);
    _productImage = (ImageButton)findViewById(R.id.productImage);

    _productDAO = new ProductDAO(getApplication()); 

    //set data from database
    _product = _productDAO.getProduct(getIntent().getExtras().getString(DataBaseKeys.PRODUCT_NAME));

    if(_product != null)
    {
        _productName.setText(_product.getName());
        _productImage.setImageBitmap(_product.getIcon());
        _productPrice.setText(""+_product.getPrice());
        _productUnit.setText(_product.getUnit());
        _productIcon = _product.getIcon();
    }           

}

Ответы [ 2 ]

4 голосов
/ 02 декабря 2011

Ну, View s в андроиде сохраняют часть своего состояния.Как и EditText сохранить его текст, чтобы вам не пришлось его сохранять onSaveInstanceState.Другие примеры: ListView сохранить позицию прокрутки.EditText также сохраняет положение прокрутки, если текст многострочный.

Но некоторые вещи, которые пользователь должен позаботиться, например, если у вас приложение для заметок, вы должны сохранить идентификатор заметки, который редактируется так, чтобычто при смене ориентации вы знаете, над чем работаете.

Это стандартный способ Android, здесь нет ничего необычного.Для получения более подробной информации см.

Сохранение состояния активности

Относительно того, что одно из ваших действий не ведет себя должным образом, из-за кода:

 _product = _productDAO.getProduct(getIntent().getExtras().getString(DataBaseKeys.PRODUCT_NAME));

if(_product != null)
{
    _productName.setText(_product.getName());
    _productImage.setImageBitmap(_product.getIcon());
    _productPrice.setText(""+_product.getPrice());
    _productUnit.setText(_product.getUnit());
    _productIcon = _product.getIcon();
}           

Выпереопределяют значения редактируемого текста.Попробуйте этот оператор журнала перед оператором if.

Log.i("EDIT_NOT_WORKING", "VALUE OF EDIT: " + _productName.getText());

Вы должны увидеть, что он напечатает введенное значение.

0 голосов
/ 06 марта 2017

Если вы не дадите идентификатор своему тексту редактирования, он не сохранит значение при изменении экрана. Необходимо указать идентификатор, чтобы значение сохранялось, даже если экран меняет ориентацию.

...