0
0

More than 1 year has passed since last update.

【android】ボタンクリック時のイベント

Posted at

はじめに

ボタンをクリックしたときに、テキストボックスの文字を変更してみようと思います。
Hello World!⇒こんにちは
こんにちは⇒HELLO
image.png
image.png

java

MainActivity.java
package com.example.testapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView txt;

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

        txt = (TextView)this.findViewById(R.id.text1);
    }

    //ボタン(こんにちは)
    public void japButton(View view){
        txt.setText(R.string.temp1);
    }

    //ボタン(HELLO)
    public void japButton2(View view){
        txt.setText(R.string.temp2);
    }
}

まず、onCreate()でレイアウトパッケージの「text1」という名前の文字列プロパティを取得しています。
japButtonjapButton2はボタンが押された時のイベントのメソッドです。

XML

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:id="@+id/out_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="japButton"
        android:text="@string/out_button_label"
        tools:ignore="UsingOnClickInXml" />


    <Button
        android:id="@+id/out_button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="japButton2"
        android:text="@string/out_button_label2"
        tools:ignore="UsingOnClickInXml" />

</LinearLayout>

android:onClick=でイベントを定義しているメソッドを指定しています。

strings.xml
<resources>
    <string name="app_name">TestApp</string>
    <string name="out_button_label">こんにちは</string>
    <string name="out_button_label2">HELLO</string>
    <string name="temp1">こんにちは</string>
    <string name="temp2">HELLO</string>
</resources>

ボタンや、テキストボックスに表示する。文字列を定義しています。

おわりに

htmlがxmlでjavascriptがjavaみたいなイメージですね。
java側で判定して、ボタンの数を増やしたりもできるのでしょうか、、

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0