android日常学习3-23 实现打字游戏

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值