今天來學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的幫助
還是完成嚕 :)