简体   繁体   中英

Set the text of the button pressed. Android development

I'm learning to create apps for android. I want to edit the text of the button that is pressed.

What I have right now works, but I want to know if there is a better way. Specifically for the lines

Button vb = (Button) v;
vb.setText(et1.getText().toString());

what is the view "v" that is being passed in? Why can't I do something like v.setText();

package mobile.threethingstodo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements View.OnClickListener {

Button b1, b2, b3;
EditText et1;
String text = "default";

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

    initialize();
}

public void initialize() {
    b1 = (Button) findViewById(R.id.button1);
    b2 = (Button) findViewById(R.id.button2);
    b3 = (Button) findViewById(R.id.button3);
    et1 = (EditText) findViewById(R.id.editText1);

    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    b3.setOnClickListener(this);
}

@Override
public void onClick(View v) {

    Button vb = (Button) v;
    vb.setText(et1.getText().toString());

}

what is the view "v" that is being passed in?

The View passed to onClick() is the View which was clicked. This is a great way to write this program since the action performed is similar for all of your buttons.

Why can't I do something like v.setText();

Because the View class does not have a setText() metohd. If you try to do this, you will get a compiler error.

You can cast View to TextView as it extends View. Then you will be introduced another problem when you want to handle multiple click event. When facing that problem, learn how each view has an I'd then use that Id to identify your target view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM