Shashi Dhar
Shashi Dhar

Reputation: 633

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.

@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);


                }
            }

    );
}

Upvotes: 1

Views: 100

Answers (3)

Nas
Nas

Reputation: 2198

Declare your views globally

Button btn;
EditText txt;

set your id in onCreate method

btn=(Button)findViewById(R.id.button);
txt=(EditText)findViewById(R.id.editText);

keep your onclicklistener as follow

    btn.setOnClickListener(
            new View.OnClickListener(){

                public void onClick(View v)
                {
                 final String newText=txt.getText().toString().trim();
                 if(newText.length()>0){
                    btn.setText(newText);
                 }


                }
            }

    );

Upvotes: 1

Dmitriy
Dmitriy

Reputation: 517

        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());
                    }
                }               
            });
        }

Upvotes: 0

Saeed Zhiany
Saeed Zhiany

Reputation: 2141

you just need define EditText variable instead of TextView and call getText method of editText and then toString method like this:

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());
            }
        }

);

Upvotes: 1

Related Questions