给按钮加监听识别
- 之前说过了我们要控制组件是要在MainActivity里面写代码
- 布局代码:
<?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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="@+id/jub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登陆"/>
</LinearLayout>
写代码前我们要有一个思路:
- 首先,要定义一个组件(按钮)
- 通过id找到这个组件(按钮)
- 在该组件(按钮)上添加监听事件
代码如下:
ackage com.example.comgzh202116;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button button;//声明一个按钮
int i=0; //记录点击次数
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.jub); //通过id找到按钮
button.setOnClickListener(new View.OnClickListener() {//添加监听
@Override
public void onClick(View v) {
i++;
button.setText("点击"+i+"次");
}
});
}
}
没点击
点击两次