Choose Empty Activity.
Enter a project name.
Choose activity_main.xml.
Add a button.
Delete TextView (Hello World) by pressing Delete key
Add android:onClick attribute inside <Button> tag
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="onButtonClicked"
tools:layout_editor_absoluteX="158dp"
tools:layout_editor_absoluteY="316dp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Let's make a message appear when a button is pressed.
You need to link the button you added in activity_main.xml to MainActivity.java.
package com.jw.messageexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClicked(View view){
Toast.makeText(this,"Button clicked",Toast.LENGTH_LONG).show();
}
}
That way, the click event from the button can be handled in the Java source.
Toast serves as a small, brief display of messages.
Press Alt + Enter to resolve import errors.
Run app
When you press the button, you can see that the message appears and disappears at the bottom of the screen.
'기타 ETC > Android Studio' 카테고리의 다른 글
안드로이드 애드몹 보상형광고 (0) | 2021.10.05 |
---|---|
안드로이드 애드몹 전면광고 (0) | 2021.10.05 |
안드로이드 SQLite 데이터베이스 CRUD 간단 예제 (0) | 2021.04.12 |
Android Paint 안드로이드 그림판 만들기 (1) | 2021.02.15 |
[Android] 애드몹(Admob) 전면 광고 달기 - 테스트 광고 (0) | 2021.01.28 |