Button
- 指定在layout文件中指定onClick属性:
android:onClick="click"
2.然后在activity中实现click这个方法
public void click(View v){
Log.i(“指定onClick属性方式”,“button is clicked”);
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="按钮被点击了吗?" />
<Button
android:id="@+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="onClick方式" />
</LinearLayout>
package com.example.linearlayoutdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView4=findViewById(R.id.textView4);
}
public void click(View v){
textView4.setText("onclick方式成功");
}
}
image.png
- 匿名内部类方式
1.在activity中添加匿名内部类
btn.setOnClickListener(new View.OnClickListener(){
@override
public void onClick(View v){
Log.i("匿名内部类方式","button is clicked");
}
});
package com.example.linearlayoutdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView4;
private Button button8;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView4=findViewById(R.id.textView4);
button8=findViewById(R.id.button8);
button8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView4.setText("匿名内部类处理事件");
}
});
}
}
image.png
网友评论