반응형

안녕하세요, 츄르 사려고 코딩하는 집사! 코집사입니다.

안녕하세요, 츄르 사려고 코딩하는 집사! 코집사입니다.

안드로이드 스튜디오에서 버튼을 눌렀을 때, 토스트 메시지가 출력되는 기능을 만들어 봅시다.

 

1. 버튼 만들기

- 저는 아래와 같이, 버튼을 하나 만들었습니다.

- 버튼의 id는 button이고, 텍스트는 알림 시작 입니다.

<소스코드 - activity_main.xml>

<?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:ads="http://schemas.android.com/apk/lib/com.google.ads"
    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="match_parent"
            android:layout_height="wrap_content"
            android:text="알림 시작" />


</androidx.constraintlayout.widget.ConstraintLayout>

2. MainActivity.java로 가서 메소드 만들기

- 저는 button의 메소드를 setOnClickListener(v)로 설정하고,

- Toast.makeText(getApplicationContext(), "알림을 시작합니다.",Toast.LENGTH_LONG).show(); 로 코드 작성하였습니다.

 

<소스코드 - MainActivity.java>

public class MainActivity extends AppCompatActivity {
    private AdView mAdView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MobileAds.initialize(this, getString(R.string.admob_app_id));

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox); 
        final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2); 
        final CheckBox checkBox3 = (CheckBox) findViewById(R.id.checkBox3); 
        Button button = (Button) findViewById(R.id.button); // 알림시작

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "알림을 시작합니다.",Toast.LENGTH_LONG).show();
            }
        });
    }

 

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기