有人可以解释descendantFocusability = afterDescendants吗?

Sta*_*wer 37 android

我很难理解descendantFocusability.非常特别afterDescendants.

有人能告诉我一个何时有用的例子?

Pra*_*nik 68

ViewGroup在寻找View焦点时定义它与其后代之间的关系.

必须是以下常量值之一.

+------------------------------------------------------------------------------------------+
|      Constant            Value            Description                                    |
+------------------------------------------------------------------------------------------+
| afterDescendants           1          The ViewGroup will get focus only if               |
|                                       none of its descendants want it.                   |
+------------------------------------------------------------------------------------------+
| beforeDescendants          0          The ViewGroup will get focus before                |
|                                       any of its descendants.                            |
+------------------------------------------------------------------------------------------+
| blocksDescendants          2          The ViewGroup will block its descendants from      |
|                                       receiving focus.                                   |
+------------------------------------------------------------------------------------------+

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

该片段是:

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

}
Run Code Online (Sandbox Code Playgroud)

根据上面的代码片段,afterDescendants用于防止listview获得焦点,以便任何一个EditTextButton可以请求焦点.

  • @SuyashChavan说您的布局充满了editTexts。当您的活动恢复时,第一个editText将成为焦点,并弹出softInputKeyboard。如果您不希望这种情况发生,并且希望用户决定先填充哪个视图,则将android:descendantFocusability =“ beforeDescendants”属性添加到父视图中,即可解决问题。 (2认同)