OnFocusChanged方法简介

onFocusChanged只能在View中重写。该方法是焦点改变的回调方法,当某个控件重写了该方法后,当焦点发生变化时,会自动调用该方法来处理焦点改变事件。该方法的签名如下。

protected void onFocusChanged(boolean gainFocus,int direction,Rect previouslyFocusedRect)

参数gainFocus:参数gainFocus表示触发该事件的View是否获得了焦点,当该控件获得焦点时,gainFocus等于true,否则等于false。

参数direction:参数direction表示焦点移动的方向,用数值表示。

参数previouslyFocusedRect:表示触发事件的View的坐标系中,前一个获得焦点的矩形区域,即表示焦点是从哪里来的。如果不可以则为null。

下面是一个简单的例子

其mianActivity的代码如下:

 package com.example.onfocuschanged;


import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;




public class MainActivity extends Activity {

MyButton myButton01;
MyButton myButton02;
MyButton myButton03;
MyButton myButton04;
MyButton myButton05;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myButton01=new MyButton(this);
        myButton02=new MyButton(this);
        myButton03=new MyButton(this);
        myButton04=new MyButton(this);
        myButton05=new MyButton(this);
        myButton01.setText("myButton01");
        myButton02.setText("myButton02");
        myButton03.setText("myButton03");
        myButton04.setText("myButton04");
        myButton05.setText("myButton05");
        LinearLayout linearLayout=new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(myButton01);
        linearLayout.addView(myButton02);
        linearLayout.addView(myButton03);
        linearLayout.addView(myButton04);
        linearLayout.addView(myButton05);
        setContentView(linearLayout);
    }
    class MyButton extends Button{
    public MyButton(Context context){
    super(context);
    }
    protected void onFocusChanged(boolean focused,int direction,Rect previouslyFocusedRect){
    Log.d("Button", this.getText()+",focused="+focused+",direction="+direction+",previouslyFocusedRect"+previouslyFocusedRect);
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

你可能感兴趣的:(Activity)