【问题标题】:EditText and button(When button is pressed value shoud be entered in edittext field)EditText 和按钮(按下按钮时应在 edittext 字段中输入值)
【发布时间】:2016-06-22 05:20:18
【问题描述】:

我正在创建一个计算器,我想在按下按钮时说 5,如何为按钮设置值 5 以及是否单击了该按钮。该值应打印在编辑文本中!!

我的源代码:

ed=(EditText)findViewById(R.id.editText);

b=(Button)findViewById(R.id.button);

gt=Double.parseDouble(ed.getText().toString());

ed.setText(""+gt);

}

【问题讨论】:

  • 完整源代码 public void add(View view) { display(); } private void display() { EditText ed; > 按钮 b;双gt;
  • 正确编辑您的问题。

标签: android android-edittext android-button


【解决方案1】:

如果我正确理解了您的问题:

你有一些带有文本或数字的按钮。 如果有人按下其中一个按钮,您想在 editText 框中显示按钮的文本吗?

如果是这样,您可以执行以下操作:

EditText myEditText = (EditText) findViewById(R.id.editText);

Button myButton0= (Button) findViewById(R.id.button0);
myButton0.setOnClickListener( new OnClickListener() {

    @Override
    public void onClick(View v) {
        //Get the button text and display it in the editText
        //This will replace all text in the editText box
        myEditText.setText(myButton0.getText().toString());

        //Or (Thanks to @cherry-wave)
        //This will append the text, instead of replacing  
        myEditText.setText(myEditText.getText() + myButton0.getText().toString());
    }
});

或者(只用一种方法处理所有按钮):
将以下行添加到布局 xml 中的所有按钮:

 android:onClick="onClick"

并将以下方法放入您的活动类文件中:

//Your onClick method
public void onClick(View v) {
    Button myButton = (Button)v;
    //Don't forget to declare your edittext
    //This will replace all text in the editText box
    myEditText.setText(myButton.getText().toString());

    //Or (Thanks to @cherry-wave)  
    //This will append the text, instead of replacing  
    myEditText.setText(myEditText.getText() + myButton.getText().toString());
}

希望对你有所帮助。

【讨论】:

  • 另外,当这真的是关于计算器时:首先获取编辑文本的文本,然后设置文本并附加点击按钮的值
  • 好一个!将其添加到解决方案中
【解决方案2】:
    Take the value from button and add to edittext . 
    Just like this .
    editText.setText(btnFive.getText().toString());
Before button click get value from editText .
String edtValue = editText.getText.toString();
Than set  editText.setText(edtValue+btnFive.getText().toString());

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2011-02-26
    • 2012-08-06
    • 2014-05-06
    • 1970-01-01
    相关资源
    最近更新 更多