Android:为什么我的 EditText 保持其值,即使方向发生变化?

发布于 2024-12-19 04:18:34 字数 8779 浏览 3 评论 0原文

这是出于好奇而提出的问题。

我最近刚刚了解到我必须关心自己保持方向变化时的活动状态。

但在我的其中一个布局中,Edittext 只是保留其值,我不明白为什么? 显然我想为其他 EditText 重现此行为...

这是布局,edittext 是 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>

这是活动的 onCreate

    @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;
        }
    });     
}

这是包含 edittexts 的另一个活动的代码不保留其状态

  <?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();
    }           

}

this is a question out of curiosity.

I recently just learned that i have to care about keeping my activity state on orientation changes myself.

But in one of my Layouts, the Edittext just keeps its value and i do not get why?
Obviously i would like to reproduce this behaviour for other EditTexts...

Heres the Layout, the edittext is 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>

and here is the onCreate for the activity

    @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;
        }
    });     
}

this is the code of another activity which contains edittexts that do not preserve their state

  <?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>

and the 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();
    }           

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青芜 2024-12-26 04:18:34

Android 中的 View 确实保留了一些状态。就像 EditText 保留其文本一样,这样您就不必在 onSaveInstanceState 中保存它。其他示例是 ListView 保持滚动位置。如果是多行文本,EditText 也会保留滚动位置。

但用户必须注意的一些事情,例如如果您有一个 Note 应用程序,则必须存储正在编辑的 Note ID,以便在方向更改时您知道自己在做什么。

这是Android的标准方式,这里没有什么异常。欲了解更多详情,请参阅。

保存 Activity 状态

关于您的一项行为不符合方面的情况是因为代码:

 _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());

您应该看到它将打印输入的值。

Well the Views in android do keep some of its state. Like EditText keep its text so you dont have to save it onSaveInstanceState. Other examples are ListView keep the scroll position. EditText also keeps scroll position if it multi-line text.

But some of the thing a user has to takecare like if you are having a Note App, you have to store Note ID which is being edited so that on orientation change you know what you are working on.

This is a standard way of Android, nothing unusual here. For more details refer.

Saving Activity State

Regarding one of your activity not behaving as aspected is because of code:

 _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();
}           

You are overriding the values of the edit text. Try this log statement before if statement.

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

You should see that it will print the entered value.

何必那么矫情 2024-12-26 04:18:34

如果您没有为 editText 提供 id,则它不会在屏幕更改时保存该值。您必须提供一个 id 以便保存该值,即使屏幕改变方向也是如此。

If you don't give an id to your editText, it won't save the value on screen change. You have to give an id so that the value is saved, even if the screen changes orientation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文