此篇就以現在常遇到的狀況下做簡易的介紹
首先我們先把一般情況下的
先把頁面畫出來
1 . activity_button.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">
<Button
android:id="@+id/buttonTest"
android:layout_width="88dp"
android:layout_height="48dp"
android:layout_marginBottom="232dp"
android:layout_marginEnd="148dp"
android:layout_marginStart="148dp"
android:layout_marginTop="231dp"
android:text="我是按鈕"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
重點來了
以下是 Java 寫法 :
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ButtonJavaActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnTest;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTest = findViewById(R.id.buttonTest);
btnTest.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonTest:
Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
以下是 Kotlin 寫法 :
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button
import android.widget.Toast
class ButtonActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var btnTest: Button;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_button)
btnTest = findViewById(R.id.buttonTest);
btnTest.setOnClickListener(this);
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.buttonTest -> {
Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show();
}
else -> {
}
}
}
}
沒有留言:
張貼留言