点击随机数变换

效果图为在这里插入图片描述

CustomRandomTextView继承至TextView

package com.example.customrandom.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

@SuppressLint("AppCompatCustomView")
public class CustomRandomTextView extends TextView {


    public CustomRandomTextView(Context context) {
        super(context);
        init();
    }

    public CustomRandomTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        ChangeText();
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ChangeText();
            }
        });
    }
    int i=0;
    private void ChangeText() {
        setText(String.valueOf(getRandom()));
        if (i%2==0){
            setBackgroundColor(Color.BLACK);
        }else {
            setBackgroundColor(Color.RED);
        }
        i++;
    }

    private int getRandom() {
        return (int) (Math.random()*9000+1000);
    }

}

xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <com.example.customrandom.view.CustomRandomTextView
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textSize="30sp"
        android:textColor="#ff0"
        />

</RelativeLayout>

猜你喜欢

转载自blog.csdn.net/qq_43580899/article/details/84639863