Button在Android Studio中需要点击两次才能正常工作(与其他人的问题不同)

huangapple 未分类评论48阅读模式
英文:

Button has to be clicked twice in Android Studio to work (different from other peoples issues)

问题

我有两个编辑文本框,它们都与各自的图像按钮关联。当我点击按钮并使用编辑文本的输入时,只有在第二次按下按钮时才起作用。基本上,我有一个大数值,当按钮被按下时,编辑文本中的任何数字都会从大数值中减去。

在同一个活动中,我还有另一个按钮,它会带您进入设置活动,但那个按钮运行得非常好,我不知道为什么这两个按钮需要双击。

XML 代码:

<ImageButton
  android:id="@+id/plusCal"
  android:layout_width="38dp"
  android:layout_height="32dp"
  android:layout_marginStart="120dp"
  android:layout_marginBottom="124dp"
  android:background="@color/white"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintStart_toStartOf="parent"
  app:srcCompat="@drawable/plus" />

活动 代码:

public class MainActivity extends AppCompatActivity {

    // 创建私有 ImageButton 对象
    private ImageButton setting_button;
    TextView Cremaining, Premaining;
    EditText MinusCal, MinusPro;
    ImageButton plusCal, plusPro;

    String calData, proData;
    SharedPreferences prefs;

    int calint, proint, Calinput, ProInput;
    String Result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        calData = prefs.getString("Cal_Total", "0");
        proData = prefs.getString("Pro_Total", "0");

        // 通过 findviewbyID 检索 TxtView
        Cremaining = (TextView) findViewById(R.id.RemainingCal);
        Premaining = (TextView) findViewById(R.id.RemainingPro);

        // 通过 findviewbyID 检索 EditButton
        MinusCal = (EditText) findViewById(R.id.EditCal);
        MinusPro = (EditText) findViewById(R.id.EditPro);

        // 通过 findViewbyID 检索 Button
        plusCal = (ImageButton) findViewById(R.id.plusCal);
        plusPro = (ImageButton) findViewById(R.id.plusProtein);

        // 从设置中获取蛋白质和卡路里,或者从结果更新
        Cremaining.setText(calData);
        Premaining.setText(proData);

        plusCal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences.Editor editor = prefs.edit();

                // 从输入卡路里中减去卡路里,然后将总数设置为 calData,保存并设置文本
                Calinput = Integer.parseInt(MinusCal.getText().toString());
                calint = Integer.parseInt(calData);
                calint -= Calinput;
                calData = String.valueOf(calint);
                editor.putString("Cal_Total", calData);
                calData = prefs.getString("Cal_Total", "0");
                Cremaining.setText(calData);

                editor.apply();
            }
        });
    }
}

忽略格式和多余的变量,我在解决问题后打算清理代码,错误处理也是如此(尝试捕获异常)

更新:我找到了解决方法:
我在使用编辑器时使用的是 .apply() 而不是 commit,而且我在执行调用的时候使用得太晚,所以我设置了值,将其保存到共享首选项中,然后在正确的流程中重新调用共享首选项,而没有提交,这会导致它获取旧值。

英文:

I have 2 edit texts and both of them are linked to their respective image buttons. When I click the buttons and use the input from edit text it only works once I press it for the second time. Basically I have a big value and any number I put in the edit text is subtracted from the big value once the button is pressed.

I have another button on the same activity that takes you to the settings activity but that one works perfectly fine, I do not know why these 2 buttons require double tap.

XML Code:

  &lt;ImageButton
    android:id=&quot;@+id/plusCal&quot;
    android:layout_width=&quot;38dp&quot;
    android:layout_height=&quot;32dp&quot;
    android:layout_marginStart=&quot;120dp&quot;
    android:layout_marginBottom=&quot;124dp&quot;
    android:background=&quot;@color/white&quot;
    app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:srcCompat=&quot;@drawable/plus&quot; /&gt;

Activity Code:

public class MainActivity extends AppCompatActivity {

//create private ImageButton Object
private ImageButton setting_button;
TextView Cremaining, Premaining;
EditText MinusCal, MinusPro;
ImageButton plusCal, plusPro;

String calData, proData;
SharedPreferences prefs;

int calint, proint, Calinput, ProInput;
String Result;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    calData = prefs.getString(&quot;Cal_Total&quot;,&quot;0&quot;);
    proData = prefs.getString(&quot;Pro_Total&quot;,&quot;0&quot;);


    //retrieve TxtView using findviewbyID
    Cremaining = (TextView) findViewById(R.id.RemainingCal);
    Premaining = (TextView) findViewById(R.id.RemainingPro);

    //Retrieve EditButton using findviewbyID

    MinusCal = (EditText)findViewById(R.id.EditCal) ;
    MinusPro = (EditText)findViewById(R.id.EditPro);

    //Retrieve Button using findViewbyID
    plusCal = (ImageButton)findViewById(R.id.plusCal);
    plusPro = (ImageButton)findViewById(R.id.plusProtein);



    //Set Protein and Calories either from settings or update from result
        Cremaining.setText(calData);
        Premaining.setText(proData);

    plusCal.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {

            SharedPreferences.Editor editor = prefs.edit();

            //Subtract Calories from Input calories, then set total to calData and save and set text
            Calinput = Integer.parseInt(MinusCal.getText().toString());
            calint = Integer.parseInt(calData);
            calint -= Calinput;
            calData = String.valueOf(calint);
            editor.putString(&quot;Cal_Total&quot;, calData);
            calData = prefs.getString(&quot;Cal_Total&quot;,&quot;0&quot;);
            Cremaining.setText(calData);




            editor.apply();

        }
                                   });

Ignore the formatting and redundant variables, I aim to clean up the code once I have the issue working, same goes with any error handling (try catches)

UPDATE: I figured it out:
The editor, I am using .apply() instead of commit and I am using it late in the call of execution, so i set the value, save it to shared preferences, and then recall the shared preferences without commiting in the right flow which causes it too pick up the old value.

答案1

得分: 0

当您编辑EditText时,该视图将获得焦点。因此,第一次点击将使其失去焦点(编辑插入符将消失),第二次点击可以转到按钮或任何其他视图。

您可以这样做:

editText.setOnFocusChangeListener```,然后如果```focus == false```,您可以执行所需的操作

或者您可以这样做```java
editText.addTextChangedListener()```,并重写您想要的方法
您可以在其中触发所需的操作并且当用户输入一个值时您可以自动进行计算在这种情况下不需要按钮

或者您可以这样做```java
editText.setOnKeyListener()```,并重写```onKey()```,并在检测到按下回车键时执行类似以下操作
```java
if ((keyevent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
{
  //执行您想要的操作
}
英文:

When you edit the editText, that view has focus. So the first tap will make it lose focus (the edit caret will disappear) and the second tap can go to the button or any other views.

You can do
editText.setOnFocusChangeListener and then if the focus == false you can run the action you want.

Or you can do editText.addTextChangedListener() and override the methods you want.
You can trigger the action you want in there and as the user enter a value, you can automatically do the calculation. No need for the buttons in this case.

Or you can editText.setOnKeyListener() and override onKey() and detect when the enter key is tapped do something like this:

if ((keyevent.getAction() == KeyEvent.ACTION_DOWN) &amp;&amp; (keyCode == KeyEvent.KEYCODE_ENTER))
{
 //perform the action you want
}

huangapple
  • 本文由 发表于 2020年4月6日 11:19:52
  • 转载请务必保留本文链接:https://java.coder-hub.com/61052476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定