今天来学Button

Buootn onClick使用方法 设置监听器来监听按钮的触控还有三种可以接到click的方式

public class ButtonClickActivity extends AppCompatActivity implements View.OnClickListener{

private TextView tv_result;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_button_click);
Button btn_single = findViewById(R.id.btn_single);
tv_result = findViewById(R.id.tv_result);
btn_single.setOnClickListener(new MyOnClickListener(tv_result));

Button btn_public = findViewById(R.id.btn_public);
btn_public.setOnClickListener(this);
}

@Override
public void onClick(View v){
if(v.getId()==R.id.btn_public){
String desc = String.format("%s 你点了按钮: %s", DateUtil.getnowTime(),((Button)v).getText());
tv_result.setText(desc);
}
}

static class MyOnClickListener implements View.OnClickListener{
private final TextView tv_result;

public MyOnClickListener(TextView tv_result){
this.tv_result = tv_result;
}
@Override
public void onClick(View v){
String desc = String.format("%s 你点了按钮: %s", DateUtil.getnowTime(),((Button)v).getText());
tv_result.setText(desc);
}
}
}

LongClick的使用方式 小于500ms=>onclick 大于500ms=>longclick

public class ButtonLongClickActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_button_long_click);
TextView tv_result = findViewById(R.id.tv_result);
Button btn_longclick = findViewById(R.id.btn_longclick);
btn_longclick.setOnLongClickListener(view -> {
String desc = String.format("%s 你点了按钮: %s", DateUtil.getnowTime(),((Button)view).getText());
tv_result.setText(desc);
return true;
});
}
}

按钮的Enable和Disable

public class ButtonEnableActivity extends AppCompatActivity implements View.OnClickListener {

private Button button_result;
private TextView tv_result;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_button_enable);
Button button_enable = findViewById(R.id.btn_enable);
Button button_disable = findViewById(R.id.btn_disable);
button_result = findViewById(R.id.btn_result);
tv_result = findViewById(R.id.tv_result);

button_enable.setOnClickListener(this);
button_disable.setOnClickListener(this);
button_result.setOnClickListener(this);
}
@Override
public void onClick(View view){
if(view.getId() == R.id.btn_enable){
button_result.setEnabled(true);
button_result.setTextColor(Color.BLACK);
} else if (view.getId() == R.id.btn_disable) {
button_result.setEnabled(false);
button_result.setTextColor(Color.GRAY);
} else if (view.getId() == R.id.btn_result) {
String desc = String.format("%s 你点了按钮: %s", DateUtil.getnowTime(),((Button)view).getText());
tv_result.setText(desc);
}
}
}

今天的button比较多java语法的部分涉及到比较多public protected还有有关静态跟动态变数的差别理解上比较困难一些些但有chatgpt的帮助还是完成噜 :)