Android Button Works Only on the second Click

2019-02-25 19:00发布

I am Developing my first android Calculator app. I'm stuck with a single defect. I have added few buttons and on clicking those buttons, it will put the respectives text on the EditText Field. The Main Problem is described below, When on running the project, the buttons have to be clicked twice to put the respective text on the EditText field for the first time. For example, Button1 puts '1' on the EditText field on click. When on run, First click on that button does nothing. Only on the second click it puts '1' on the EditText field.

The Code follows,

XML Button and EditField,

<EditText
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ellipsize="end"
        android:ems="10"
        android:gravity="right"
        android:hint="@string/textView1" />
 <Button
        android:id="@+id/button1"        
        android:layout_width="60dp"       
        android:layout_height="60dp"
        android:hint="@string/button1"
        android:onClick="set1" />

MainActivity.java

The respective function for Button onClick,

public void set1(View v){
    final Button button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new OnClickListener(){

            public void onClick(View v)
            {
                EditText tv = (EditText) findViewById(R.id.textView1);
                String text=tv.getText().toString();
                tv.setText(text+"1");
            }
    });

}

2条回答
可以哭但决不认输i
2楼-- · 2019-02-25 19:30

Change your set1() method as follows,

public void set1(View v)
{
    EditText tv = (EditText) findViewById(R.id.textView1);
    String text=tv.getText().toString();
    tv.setText(text+"1");
}
查看更多
做自己的国王
3楼-- · 2019-02-25 19:43

If you are calling your set1() method onClick of button in xml then you don't need to find ID for button in that method again. So simply it looks like,

public void set1(View v)
{
  EditText tv = (EditText) findViewById(R.id.textView1);
  String text=tv.getText().toString();
  tv.setText(text+"1");
}

Now in your xml for button will be

android:onClick="set1"
查看更多
登录 后发表回答