【问题标题】:Can someone explain descendantFocusability = afterDescendants?有人可以解释 descendantFocusability = afterDescendants 吗?
【发布时间】:2016-09-21 20:48:39
【问题描述】:

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

谁能给我举个例子,说明这在什么时候有用?

【问题讨论】:

    标签: android


    【解决方案1】:

    在寻找 View 以获取焦点时定义 ViewGroup 与其后代之间的关系。

    必须是以下常量值之一。

    +-------------------------------------------------- -----------------------------------------+ |常数值说明 | +-------------------------------------------------- -----------------------------------------+ | afterDescendants 1 只有在以下情况下 ViewGroup 才会获得焦点 | |它的后代没有一个想要它。 | +-------------------------------------------------- -----------------------------------------+ | beforeDescendants 0 ViewGroup 将在之前获得焦点 | |它的任何后代。 | +-------------------------------------------------- -----------------------------------------+ | blocksDescendants 2 ViewGroup 将阻止它的后代 | |接收焦点。 | +-------------------------------------------------- -----------------------------------------+

    您可以查看完整示例here

    sn-p 是:

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

    根据上面的 sn-p,afterDescendants 用于防止 listview 获得焦点,以便 EditTextButton 可以请求焦点。

    注意:上面提供的链接已损坏。代码请参考我的Gist

    【讨论】:

    • 嘿Pranav,我仍然很不确定为什么它真的有用。你能举一些现实生活中的例子吗?
    • @SuyashChavan 说你有一个充满编辑文本的布局。当您的活动恢复时,第一个 editText 获得焦点并弹出 softInputKeyboard。如果您不希望这种情况发生,并且希望用户决定首先填写哪个视图,则将属性 android:descendantFocusability="beforeDescendants" 添加到父视图中,您的问题就解决了。
    猜你喜欢
    • 2012-05-29
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多