《步骤化》利用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();
            }
        });
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章