《步驟化》利用Toast與TextView顯示記錄你點擊的次數

如題:我點擊按鈕一下,按鈕中文本信息更改,同時Toast文本框與TextView裏顯示記錄你點擊了多少次
如圖,編譯後的結果程序編譯的結果圖
編譯工具:android studio 3.5.2
整體代碼非常簡單,幾步完成,適合新手學習操作;
主頁面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:layout_marginEnd="11dp"
        android:layout_marginRight="11dp"
        android:text="點擊"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="79dp"
        android:hint="內容在此顯示"
        android:text=""
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity主代碼

package com.example.a201911191x;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    private Button button;
    private TextView textView;
    int count,count1;//初始化數值
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button) findViewById(R.id.button);
        textView=(TextView) findViewById(R.id.textView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
                public void onClick(View v) {
                //點擊一次按鈕,更改其中的文字信息,同時count與count1加1,TextView框和Toast框裏顯示你點擊的次數
                button.setText("再點擊一次");
                textView.setText("您點擊了"+(++count)+"次");
                Toast.makeText(MainActivity.this,"你點擊了"+(++count1)+"次",Toast.LENGTH_SHORT).show();
            }
        });
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章