簡體   English   中英

如何更改按鈕文本 onClick?

[英]How can I change a button text onClick?

我是 Android 新手,在我的課堂上,我們必須編寫一個程序,每次按下按鈕時計數都會增加,並且該數字會顯示在按鈕內。 例如,按鈕從 0 開始,我單擊該按鈕並將文本從 0 更改為 1,然后再次單擊它從 1 變為 2 等等,但按鈕中的數字會發生變化。 是否可以在不使用 TextView 的情況下執行此類操作?

這是我在 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: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:onClick="countUp"
        android:text="0"
        tools:layout_editor_absoluteX="72dp"
        tools:layout_editor_absoluteY="61dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

這就是我在 MainActivity.java 上的內容

package com.example.tapgrid;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button showValue;
    int counter = 0;

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

        showValue = (Button) findViewById(R.id.button);
    }

    public void countUp (Button view) {
        counter++;
        showValue.setText(Integer.toString(counter));
    }

}

EditText 只接受字符串值,因為計數器變量是一個整數,因此應用程序崩潰,最好將其轉換為字符串,然后將其設置為 edittext

showValue.setText(String.valueOf(counter));

您需要在偵聽單擊事件的按鈕上設置 onClick 偵聽器

findViewById(R.id.button).setOnClickListener(clickListener);
...

private View.OnClickListener clickListener = v -> {
    int count = Integer.parseInt(((Button) v).getText().toString());
    ((Button) v).setText(String.valueOf(++count));
};
public class MainActivity extends AppCompatActivity {

    Button button;

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

        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str = (String) button.getText();
                int i = Integer.parseInt(str);
                button.setText(String.valueOf(++i));

            }
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM