定期自动更改两个按钮之间的焦点

时间:2012-02-09 17:09:12

标签: android

package com.example.helloandroid;

import java.util.Timer;  
import java.util.TimerTask;  

import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.util.Log;

import android.view.View;

import android.widget.Button;


public class HelloandroidActivity extends Activity {

/** Called when the activity is first created. */

Button mybtn0,mybtn1;

private Handler mhandler= new Handler();

Timer timer= new Timer();

String s=new String(" ");

int delay=0;

int period=5000;

int var=0;

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Object o=null;
    // o.toString();
    // TextView tv = new TextView(this);
    // tv.setText("Hello Andriod");

    setContentView(R.layout.main);
    mybtn0= (Button)findViewById(R.id.number_button);
    //mybtn.requestFocus();
    mybtn0.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            mybtn0.clearFocus();
        }
    });
    // mybtn2= (Button)findViewById(R.id.contact_button);
    //setUpFocus();

    try
    {

    mybtn1=(Button)findViewById(R.id.contact_button);   
    //mybtn2= (Button)mybtn.focusSearch(View.FOCUS_DOWN);
    mybtn1.requestFocus();
    mybtn0.clearFocus();

    }
    catch(Exception e)
    {
            Log.e("focus change","focus failed",e);
    } 


    timer.scheduleAtFixedRate(new TimerTask(){

        public void run()
        { 

            switch(var)
            {

            case 0: mybtn0.clearFocus();
                    mybtn1.requestFocus();
                    break;

            case 1: mybtn1.clearFocus();
                    mybtn0.requestFocus();
                break;
            default: break;
            }

            var= (var+1)%2;


        }

    }, delay, period);

}

我已经使用上面的代码使用计时器在两个按钮之间完成自动更改焦点。但我得到“从错误的线程异常调用”。 我认为这是因为计时器。请有人更正此代码,并提供有关如何使用Handler类实现此示例的示例代码。

2 个答案:

答案 0 :(得分:0)

将您的计时器.schedule()更改为如下所示

    timer.scheduleAtFixedRate(new TimerTask(){

    public void run()
    { 


        mHandler.sendEmptyMessage(var); // <--- I suggest you camelCase your variable names so "mhandler" should be "mHandler", it will make them easier to read at a glance.
        var= (var+1)%2;


    }

}, delay, period);

然后将此处理程序实例化添加到onCreate()方法中的某些位置:

mHandler = new Handler() {
     public void handleMessage(Message msg) {
            if(msg.what == 0){
                mybtn0.clearFocus();
                mybtn1.requestFocus();
            }else if(msg.what == 1){
                mybtn1.clearFocus();
                mybtn0.requestFocus();
            }
     }
}

您也可以一起跳过TimerTask,然后使用Handler进行调度。查看.sendEmptyMessageDelayed() method

答案 1 :(得分:0)

该代码需要在UI线程上执行。有Activity.runOnUiThread