MainActivity代码
package com.mz.demo;
import org.w3c.dom.Text;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView tv_in;
private int count=1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv_in=(TextView)this.findViewById(R.id.tv1);
//处理键盘事件
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
//1.首先获得用户输入的字符
char ch=Character.toLowerCase(event.getDisplayLabel());
if(ch==tv_in.getText().charAt(count-1) && event.getAction()==KeyEvent.ACTION_DOWN){
//将文字更改类型
SpannableString ss=new SpannableString(tv_in.getText().toString());
ss.setSpan(new ForegroundColorSpan(Color.RED), 0, count, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//更改了字符的颜色
ss.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, count, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//更改了字符
count++;
tv_in.setText(ss);
}
if(count==tv_in.length()){
Toast toast=Toast.makeText(MainActivity.this,"成功!",Toast.LENGTH_LONG);
toast.show();
}
return super.onKeyDown(keyCode, event);
}
}
需要注意的是,在打完所有字母后,如果再继续输入就造成溢出
main.xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/content"
android:textSize="20sp" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, MainActivity!</string>
<string name="app_name">WriteDemo01</string>
<string name="content">are you ok mi fans do you want a mi band </string>
</resources>