有人能解释一下 descendantFocusability = afterDescendants 是什么意思吗?

77
我很难理解 "descendantFocusability",尤其是 "afterDescendants"。有人能给我一个使用时的例子吗?
1个回答

117

定义了当查找要获得焦点的视图时,ViewGroup和其后代之间的关系。

必须是以下常量值之一。

+------------------------------------------------------------------------------------------+
|      常量名                 值               描述                                       |
+------------------------------------------------------------------------------------------+
| afterDescendants           1          只有当没有子项想要获取焦点时,ViewGroup才会获取焦点。 |
+------------------------------------------------------------------------------------------+
| beforeDescendants          0          在任何子项之前,ViewGroup将获取焦点。              |
+------------------------------------------------------------------------------------------+
| blocksDescendants          2          ViewGroup将阻止其子项接收焦点。                    |
+------------------------------------------------------------------------------------------+

您可以在此处查看完整示例。

代码片段:

public void onItemSelected(AdapterView<?> parent, View view,
        int position, long id) {
    ListView listView = getListView();
    Log.d(TAG, "onItemSelected gave us " + view.toString());
    Button b = (Button) view.findViewById(R.id.button);
    EditText et = (EditText) view.findViewById(R.id.editor);
    if (b != null || et != null) {
        // Use afterDescendants to keep ListView from getting focus
        listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
        if(et!=null) et.requestFocus();
        else if(b!=null) b.requestFocus();
    } else {
        if (!listView.isFocused()) {
            // Use beforeDescendants so that previous selections don't re-take focus
            listView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            listView.requestFocus();
        }
    }

}

根据上面的片段,afterDescendants被用来防止listview获得焦点,以便EditTextButton可以请求焦点。
注意:上面提供的链接已经失效,请参考我的Gist中的代码。

嘿,Pranav,我仍然不太确定它真正有用的原因。你能否举些现实生活中的例子? - Suyash Chavan
15
@SuyashChavan说你有一个布局里面有很多EditText。当你的活动恢复时,第一个EditText会获得焦点并弹出软键盘。如果你不想这样发生,而是希望用户决定先填写哪个视图,你可以在父视图中添加属性android:descendantFocusability="beforeDescendants",这样问题就解决了。 - Nikos Hidalgo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接