android中设置控件获得焦点

android中,要使控件获得焦点,需要先setFocus,再requestFocus。

以Button为例:

btn.setFocusable(true);
btn.setFocusableInTouchMode(true);

btn.requestFocus();
btn.requestFocusFromTouch();

或者在xml文件里设置:

 <RadioGroup
            android:id="@+id/auxilTabBarId"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"

            <-- 如下,缺一不可-->
            android:focusable="true"
            android:focusableInTouchMode="true">

获得失去焦点的监听器:

btn.setOnFocusChangeListener(new OnFocusChangeListener() {
  
  @Override
  public void onFocusChange(View v, boolean hasFocus) {
   // TODO Auto-generated method stub
   if (hasFocus) {
    btn_box.setBackgroundResource(R.drawable.book_green);
   }else {
    btn_box.setBackgroundResource(R.drawable.book);
   }   
  }
 });


 

posted @ 2019-11-15 15:02  广金  阅读(5770)  评论(0编辑  收藏  举报