布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.longfei.smsyan.MainActivity"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_margin="5dp" android:layout_height="50dp" android:text="发送消息" android:gravity="center" android:background="@drawable/bg_identify_code_normal" /> </RelativeLayout>
Activity代码
package com.example.longfei.smsyan; import android.graphics.Color; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView mTextView; // 总倒计时时间 private static final long MILLIS_IN_FUTURE = 60 * 1000; // 每次减去1秒 private static final long COUNT_DOWN_INTERVAL = 1000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); mTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 设置按钮为不可点击,并修改显示背景 mTextView.setEnabled(false); mTextView.setBackgroundResource(R.drawable.bg_identify_code_press); // 开始倒计时 new CountDownTimer(MILLIS_IN_FUTURE, COUNT_DOWN_INTERVAL) { @Override public void onTick(long millisUntilFinished) { // 刷新文字 mTextView.setText(millisUntilFinished / COUNT_DOWN_INTERVAL+ "秒后可重新发送"); SpannableString spannableString = new SpannableString(mTextView.getText().toString()); //获取按钮上的文字 ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//将倒计时的时间设置为红色 mTextView.setText(spannableString); } @Override public void onFinish() { // 重置文字,并恢复按钮为可点击 mTextView.setText("重新获取验证码"); mTextView.setEnabled(true);//重新获得点击 mTextView.setBackgroundResource(R.drawable.bg_identify_code_normal); //还原背景色 } }.start(); } }); } }
图片界面shape
bg_identify_code_normal
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FF9933" /> <!--填充色 透明--> <corners android:radius="8dp" /> <!-- 圆角 --> </shape>
bg_identify_code_press
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#C0C0C0" /> <!--填充色 透明--> <corners android:radius="8dp" /> <!-- 圆角 --> </shape>