[英]How to change a text on the click of a button in android?
I need to set text of a button by taking value from edit text ,when button is clicked it has to change its text to the text specified in Edittext. 我需要通过从编辑文本中获取值来设置按钮的文本,单击按钮时必须将其文本更改为Edittext中指定的文本。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn=(Button)findViewById(R.id.button);
assert btn != null;
btn.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v)
{
TextView txt=(TextView)findViewById(R.id.editText);
btn.setText((CharSequence) txt);
}
}
);
}
you just need define EditText
variable instead of TextView
and call getText
method of editText and then toString
method like this: 您只需要定义EditText
变量而不是TextView
并调用editText的getText
方法,然后调用如下的toString
方法:
final Button btn=(Button)findViewById(R.id.button);
assert btn != null;
btn.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v)
{
EditText txt = (EditText)findViewById(R.id.editText);
btn.setText(txt.getText().toString());
}
}
);
Declare your views globally 在全球范围内发表您的意见
Button btn;
EditText txt;
set your id in onCreate method 在onCreate方法中设置您的ID
btn=(Button)findViewById(R.id.button);
txt=(EditText)findViewById(R.id.editText);
keep your onclicklistener as follow 保持您的onclicklistener如下
btn.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v)
{
final String newText=txt.getText().toString().trim();
if(newText.length()>0){
btn.setText(newText);
}
}
}
);
final Button btn = (Button)findViewById(R.id.button);
if (btn != null) {
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText et = (EditText)findViewById(R.id.editText);
if (et != null){
Button btn = (Button)view;
btn.setText(et.getText());
}
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.