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);
   }   
  }
 });


 

發佈了81 篇原創文章 · 獲贊 15 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章