Android 技巧记录

1.取消EditText自动获取焦点

  在项目中,一进入一个页面, EditText默认就会自动获取焦点,弹出输入法界面,很不友好。那么如何取消这个默认行为呢?

  解决之道:在EditText的父级控件中找一个,设置成android:focusable="true" android:focusableInTouchMode="true",并且使用<requestFocus />来获取焦点即可。

  示例代码:

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"  
    android:focusableInTouchMode="true">

    <requestFocus />

    <EditText
         android:layout_width="match_parent"
         android:layout_height="wrap_content" />

</LinearLayout>
2.Android中组件焦点抢占问题解决

  在项在android中经常会出现焦点抢占的情况,在本文第一点中已经提出了一种解决方案,在部分情况下是可行的。然而在有些时候有多个组件抢占焦点,使得1中的方案并不能正确执行,例如在使用Searchview且指定了其默认展开时【android:iconifiedByDefault="false"】,其父组件并不能获取焦点,此时,考虑在父组件中添加如下属性:android:descendantFocusability

  • android:descendantFocusability="blocksDescendants"      //会覆盖子类控件而直接获得焦点android:focusable="false" 
  • android:descendantFocusability="beforeDescendants"  //会优先其子类控件而获取到焦点
  • android:descendantFocusability="afterDescendants"        //只有当其子类控件不需要获取焦点时才获取焦点
原文地址:https://www.cnblogs.com/orange-tree/p/3824106.html