简体   繁体   English

当方向改变时 EditTexts 不起作用?

[英]EditTexts aren't working when orientation changes?

I am needing to reformat an existing Android app to have a landscape version.我需要重新格式化现有的 Android 应用程序以获得横向版本。 It uses a TextWatcher to calculate a tip amount when numbers are entered into 2 EditTexts (bill amount & tip percent).当数字输入到 2 个 EditTexts(账单金额和小费百分比)时,它使用 TextWatcher 来计算小费金额。 It works by itself, but when I add a second layout, the TextWatcher stops working and doesn't calculate anything.它自己工作,但是当我添加第二个布局时,TextWatcher 停止工作并且不计算任何内容。 It rotates and looks how I want it to, but doesn't function.它旋转并看起来像我想要的那样,但不起作用。 My landscape layout has all the same parts as the portrait with the same EditText & TextView IDs.我的横向布局与具有相同 EditText 和 TextView ID 的纵向布局具有相同的部分。 This is what I am using to change the layouts:这是我用来更改布局的内容:

package com.example.tiporientation;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import java.text.NumberFormat;

public class MainActivity extends AppCompatActivity {

    private TipCalculator tipCalc;
    private NumberFormat money = NumberFormat.getCurrencyInstance();
    private EditText billEditText;
    private EditText tipEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tipCalc = new TipCalculator(.17f,100);
        setContentView(R.layout.activity_main);

        billEditText = findViewById(R.id.EDIT_BillAmount);
        tipEditText = findViewById(R.id.EDIT_EnterTip);

        //create inner-class for this... puts it at bottom of MainActivity
        //TextChangeHandler is a "listener"
        //attach it to our EDIT texts, so it is listening to changes in bill $ & tip %
        TextChangeHandler tch = new TextChangeHandler();
        billEditText.addTextChangedListener(tch);
        tipEditText.addTextChangedListener(tch);
        Configuration config = getResources().getConfiguration();
        modifyLayout(config);
    }

    private void modifyLayout(Configuration newConfig) {
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
            setContentView(R.layout.activity_main_landscape); //we create new XML for this layout
        else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
            setContentView(R.layout.activity_main);
    }

    public void onConfigurationChanged(Configuration newConfig) {
        Log.w("MainActivity", "Inside onConfigurationChanged");
        super.onConfigurationChanged(newConfig);
        modifyLayout(newConfig); //if orientation changes again, send back to modifyLayout
    }

    public void calculate () {
        //convert edit texts to a string ???
        String billString = billEditText.getText().toString();
        String tipString = tipEditText.getText().toString();

        //2 text views from XML
        TextView tipTextView = findViewById(R.id.TXT_TipTotal);
        TextView totalTextView = findViewById(R.id.TXT_TotalAmount);

        try {
            //convert billString to float & tipString to int -- can't do math with strings
            float billAmount = Float.parseFloat(billString);
            int tipPercent = Integer.parseInt(tipString);
            //update the model -- referencing TipCalculator class!
            tipCalc.setBill(billAmount);
            tipCalc.setTip(.01f * tipPercent);
            //ask model to calculate
            float tip = tipCalc.tipAmount();
            float total = tipCalc.totalAmount();
            //update view with formatted tip & total amount
            tipTextView.setText(money.format(tip));
            totalTextView.setText(money.format(total));
        } catch(NumberFormatException nfe) { }
    }

    //create implements... select all 3 they are then stubbed out in the class
    private class TextChangeHandler implements TextWatcher {
        @Override
             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
             public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override
             public void afterTextChanged(Editable s) {
             calculate();
        }
    }
}

Manifest:显现:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tiporientation">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:configChanges="orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

With the onConfigurationChanged callback your activity is destroyed and re-created.使用 onConfigurationChanged 回调,您的活动将被销毁并重新创建。 Values in your text fields can be stored in the savedInstanceState and then retrieved in onCreate.文本字段中的值可以存储在savedInstanceState ,然后在onCreate 中检索。

I am not entirely sure, but I think what happens here is:我不完全确定,但我认为这里发生的事情是:

  • Phone rotates手机旋转
  • Phone recreates the activity (your onCreate runs)电话重新创建活动(您的 onCreate 运行)
  • you receive the onConfiguration callback您收到 onConfiguration 回调
  • there you assign a new contentView(_landscape)在那里你分配一个新的 contentView(_landscape)
  • and with this you destroy the layout just rendered in onCreate and your listeners用这个你破坏了刚刚在 onCreate 和你的听众中呈现的布局

Your onCreate has already run, thus your TextWatcher was attached to a layout you just destroyed with your setContentView call from modifyLayout .您的onCreate已经运行,因此您的TextWatcher已附加到您刚刚使用来自modifyLayout的 setContentView 调用销毁的布局。

I still think you should let android manage this for you, but to solve the problem, I suggest:我仍然认为你应该让android为你管理这个,但为了解决这个问题,我建议:

  • remove the code from onCreate beginning with the first findViewById up to (and including) the .addTextWatcher lines从 onCreate 中删除代码,从第一个 findViewById 开始直到(并包括) .addTextWatcher 行

  • remove the other clutter with an additional modifyLayout call from your onCreate从您的 onCreate 中通过额外的 modifyLayout 调用删除其他混乱

  • put this code in a method, say connectWatchers将此代码放入一个方法中,例如connectWatchers

  • call this method from onCreateonCreate调用此方法

  • call this method from modifyLayoutmodifyLayout调用此方法

It should look like this:它应该是这样的:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tipCalc = new TipCalculator(.17f,100);
    setContentView(R.layout.activity_main);
    connectWatchers();
}

private void modifyLayout(Configuration newConfig) {
    if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
        setContentView(R.layout.activity_main_landscape); //we create new XML for this layout
    else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
        setContentView(R.layout.activity_main);

    connectWatchers();
}

public void onConfigurationChanged(Configuration newConfig) {
    Log.w("MainActivity", "Inside onConfigurationChanged");
    super.onConfigurationChanged(newConfig);
    modifyLayout(newConfig); //if orientation changes again, send back to modifyLayout
}

private void connectWatchers() {
    billEditText = findViewById(R.id.EDIT_BillAmount);
    tipEditText = findViewById(R.id.EDIT_EnterTip);
    TextChangeHandler tch = new TextChangeHandler();
    billEditText.addTextChangedListener(tch);
    tipEditText.addTextChangedListener(tch);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM