Android development study notes (13) event handling

Event processing (two ways):
Insert picture description here
1. Callback method
Example:
Insert picture description here
Source code:
EventActivity.java

public void changeText(View view)
    {
        TextView tv= findViewById(R.id.text_view);
        tv.setText(R.string.newStr);
        this.setTitle("这是一个新的标题");
    }

EventActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
>
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="这是一段文字"
        android:gravity="center"
        android:layout_marginTop="50dp"
        ></TextView>

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击我"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:onClick="changeText"
        >
    </Button>
</LinearLayout>

The interaction is mainly achieved through the onClick event

2. Based on the monitoring interface
EventActivity.java

public class EventActivity extends AppCompatActivity {

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

        Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(new myOnclickListener());
    }

public class myOnclickListener implements View.OnClickListener
    {

        @Override
        public void onClick(View v) {
            TextView tv= findViewById(R.id.text_view);
            tv.setText(R.string.newStr);
            EventActivity.this.setTitle("这是一个新的标题");
        }
    }
}

Another condensed way of writing:

public class EventActivity extends AppCompatActivity {

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

        Button btn = findViewById(R.id.btn);
        //btn.setOnClickListener(new myOnclickListener());

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView tv= findViewById(R.id.text_view);
                tv.setText(R.string.newStr);
                EventActivity.this.setTitle("这是一个新的标题");
            }
        });
    }

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq1198768105/article/details/113832663