Android问题记录02_点击RecyclerView headView 中的editText等控件导致焦点变化,recyclerView莫名滑动

1.问题现象

点击recyclerView headView 中的EditText时recycleView 莫名自动滑动


image

布局代码
主布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">

<!-- 顶部栏 -->
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="56dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:theme="@style/ToolbarTheme" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="@string/title_new_card"
        android:textColor="@color/white"
        android:textSize="20sp" />

    <ImageView
        android:id="@+id/iv_back"
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:padding="7dp"
        android:src="@drawable/nav_btn_back" />

</RelativeLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white" />

</LinearLayout>

headView布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:focusable="true"
 android:id="@+id/fdfsdf"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp">

<!-- card名称 -->
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/et_card_name"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_centerVertical="true"
        android:background="@null"
        android:gravity="center_vertical"
        android:hint="@string/hint_edit_card_name"
        android:paddingRight="2dp"
        android:maxLines="1"
        android:textColor="@color/text_black"
        android:textColorHint="@color/text_hint"
        android:textSize="@dimen/font_small_3" />

</RelativeLayout>

<View
    android:id="@+id/cardNameUnderLine"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/divide_line" />

<!-- card帐号 -->
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/iv_card_id_copy"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@drawable/btn_copy" />

    <EditText
        android:id="@+id/et_card_id"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@id/iv_card_id_copy"
        android:background="@null"
        android:gravity="center_vertical"
        android:hint="@string/hint_edit_card_id"
        android:paddingRight="2dp"
        android:maxLines="1"
        android:textColor="@color/text_black"
        android:textColorHint="@color/text_hint"
        android:textSize="@dimen/font_small_3" />

</RelativeLayout>

<View
    android:id="@+id/cardIdUnderLine"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/divide_line" />

<!-- card类型 -->
<LinearLayout
    android:id="@+id/layout_card_type"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/icon_card_type"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:src="@drawable/btn_cards" />

    <TextView
        android:id="@+id/tv_card_type"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_weight="1"
        android:text="@string/str_card_type"
        android:textColor="@color/text_black"
        android:textSize="@dimen/font_small_3" />

    <ImageView
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:scaleType="center"
        android:src="@drawable/btn_up" />

</LinearLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/divide_line" />

<View
    android:layout_width="match_parent"
    android:layout_height="12dp" />

</LinearLayout>

2.问题原因

在ViewGroup中 源码

private void addViewInner(View child, int index, LayoutParams params,
        boolean preventRequestLayout) {

    if (mTransition != null) {
        // Don't prevent other add transitions from completing, but cancel remove
        // transitions to let them complete the process before we add to the container
        mTransition.cancel(LayoutTransition.DISAPPEARING);
    }

    if (child.getParent() != null) {
        throw new IllegalStateException("The specified child already has a parent. " +
                "You must call removeView() on the child's parent first.");
    }

    if (mTransition != null) {
        mTransition.addChild(this, child);
    }

    if (!checkLayoutParams(params)) {
        params = generateLayoutParams(params);
    }

    if (preventRequestLayout) {
        child.mLayoutParams = params;
    } else {
        child.setLayoutParams(params);
    }

    if (index < 0) {
        index = mChildrenCount;
    }

    addInArray(child, index);

    // tell our children
    if (preventRequestLayout) {
        child.assignParent(this);
    } else {
        child.mParent = this;
    }

   //look here!!!!!!!!!!!!!!!!    看这!!!!!!!!!!!    

   if (child.hasFocus()) {
        requestChildFocus(child, child.findFocus());
    }



    AttachInfo ai = mAttachInfo;
    if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) {
        boolean lastKeepOn = ai.mKeepScreenOn;
        ai.mKeepScreenOn = false;
        child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
        if (ai.mKeepScreenOn) {
            needGlobalAttributesUpdate(true);
        }
        ai.mKeepScreenOn = lastKeepOn;
    }

     **if (child.isLayoutDirectionInherited()) {
        child.resetRtlProperties();
     }**

    dispatchViewAdded(child);

    if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
        mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
    }

    if (child.hasTransientState()) {
        childHasTransientStateChanged(child, true);
    }

    if (child.getVisibility() != View.GONE) {
        notifySubtreeAccessibilityStateChangedIfNeeded();
    }

    if (mTransientIndices != null) {
        final int transientCount = mTransientIndices.size();
        for (int i = 0; i < transientCount; ++i) {
            final int oldIndex = mTransientIndices.get(i);
            if (index <= oldIndex) {
                mTransientIndices.set(i, oldIndex + 1);
            }
        }
    }

    if (mCurrentDragStartEvent != null && child.getVisibility() == VISIBLE) {
        notifyChildOfDragStart(child);
    }
}

在recyclerView 中

@Override
public void requestChildFocus(View child, View focused) {
    if (!mLayout.onRequestChildFocus(this, mState, child, focused) && focused != null) {
        mTempRect.set(0, 0, focused.getWidth(), focused.getHeight());

        // get item decor offsets w/o refreshing. If they are invalid, there will be another
        // layout pass to fix them, then it is LayoutManager's responsibility to keep focused
        // View in viewport.
        final ViewGroup.LayoutParams focusedLayoutParams = focused.getLayoutParams();
        if (focusedLayoutParams instanceof LayoutParams) {
            // if focused child has item decors, use them. Otherwise, ignore.
            final LayoutParams lp = (LayoutParams) focusedLayoutParams;
            if (!lp.mInsetsDirty) {
                final Rect insets = lp.mDecorInsets;
                mTempRect.left -= insets.left;
                mTempRect.right += insets.right;
                mTempRect.top -= insets.top;
                mTempRect.bottom += insets.bottom;
            }
        }

        offsetDescendantRectToMyCoords(focused, mTempRect);
        offsetRectIntoDescendantCoords(child, mTempRect);
    
       

//look here!!!!!! 看这儿!!!!!!
requestChildRectangleOnScreen(child, mTempRect, !mFirstLayoutComplete);}


    super.requestChildFocus(child, focused);
}





 @Override
public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
    return mLayout.requestChildRectangleOnScreen(this, child, rect, immediate);
}

requestChildRectangleOnScreen 在recyclerView 中的具体实现

    /**
     * Requests that the given child of the RecyclerView be positioned onto the screen. This
     * method can be called for both unfocusable and focusable child views. For unfocusable
     * child views, focusedChildVisible is typically true in which case, layout manager
     * makes the child view visible only if the currently focused child stays in-bounds of RV.
     * @param parent The parent RecyclerView.
     * @param child The direct child making the request.
     * @param rect The rectangle in the child's coordinates the child
     *              wishes to be on the screen.
     * @param immediate True to forbid animated or delayed scrolling,
     *                  false otherwise
     * @param focusedChildVisible Whether the currently focused view must stay visible.
     * @return Whether the group scrolled to handle the operation
     */
    public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect,
            boolean immediate,
            boolean focusedChildVisible) {
        int[] scrollAmount = getChildRectangleOnScreenScrollAmount(parent, child, rect,
                immediate);
        int dx = scrollAmount[0];
        int dy = scrollAmount[1];
        //here 滚动!!! 粗暴点 屏蔽这一段就不滚动了
        if (!focusedChildVisible || isFocusedChildVisibleAfterScrolling(parent, dx, dy)) {
            if (dx != 0 || dy != 0) {
                if (immediate) {
                    parent.scrollBy(dx, dy);
                } else {
                    parent.smoothScrollBy(dx, dy);
                }
                return true;
            }
        }
        return false;

}

3.解决办法

自定义layoutManager

/**
 * 为了解决recycle人View上添加的headView 中的EditText等控件获取了焦点导致RecyclerView 莫名滚动
 */
class FoucsLinearLayoutManager extends LinearLayoutManager {

    public FoucsLinearLayoutManager(Context context) {
        super(context);
    }

    public FoucsLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public FoucsLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }


    /**
     *   public boolean requestChildRectangleOnScreen (View child, Rect rectangle, boolean immediate)
     * <p>
     *   当组里的某个子视图需要被定位在屏幕的某个矩形范围时,调用此方法。重载此方法的ViewGroup可确认以下几点:
     * <p>
     *   * 子项目将是组里的直系子项
     *   * 矩形将在子项目的坐标体系中
     *   重载此方法的ViewGroup应该支持以下几点:
     *   * 若矩形已经是可见的,则没有东西会改变
     *   * 为使矩形区域全部可见,视图将可以被滚动显示
     *   参数
     *   child        发出请求的子视图
     *   rectangle    子项目坐标系内的矩形,即此子项目希望在屏幕上的定位
     *   immediate   设为true,则禁止动画和平滑移动滚动条
     * <p>
     *   返回值
     *   进行了滚动操作的这个组(group),是否处理此操作。
     *
     * @param parent
     * @param child
     * @param rect
     * @param immediate
     * @return
     */
    @Override
    public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect, boolean immediate) {

//这里的child 是整个HeadView 而不是某个具体的editText
        LogUtil.e("requestChildRectangleOnScreen()====> chlild==" + child.getId() + "parent==" + parent.getId());
        return false;
    }

    @Override
    public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect, boolean immediate, boolean focusedChildVisible) {

//这里的child 是整个HeadView 而不是某个具体的editText
        LogUtil.e("requestChildRectangleOnScreen( focusedChildVisible=)====> chlild==" + child.getId() + "parent==" + parent.getId());
        return false;
    }
}

替换掉原来的LInearLayoutManager

mRecyclerView = findViewById(view, R.id.recyclerView);
mRecyclerView.setLayoutManager(new FoucsLinearLayoutManager(getContext()));

参考:http://blog.csdn.net/qq_18480625/article/details/54923796

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,290评论 6 491
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,107评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,872评论 0 347
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,415评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,453评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,784评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,927评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,691评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,137评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,472评论 2 326
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,622评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,289评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,887评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,741评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,977评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,316评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,490评论 2 348

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,756评论 25 707
  • 从上周五开始,我每天早上5:30分起床晨跑。 到今天为止,我觉得非常棒。跑步让我得到以下的好处: 1,身体健康,充...
    dennypan阅读 163评论 0 1
  • 眼前的事总会遮挡住事物的本质。只因为身边还有很多爱你的人在陪着你。 01 父亲最近经常摔跤。母亲向忆成抱怨。 父亲...
    时光恰巧阅读 203评论 0 0
  • 最早对网游端正认识是在十五年前,当时我还是一个本科狗,泡在一留学BBS坛子里当一个小斑竹,里面尽是大神,用一句话来...
    船长辛巴达阅读 376评论 3 0
  • NSInvocation 和方法签名 NSInvocation 是命令模式的一种实现。它把一个目标、一个选择器、一...
    要上班的斌哥阅读 8,067评论 0 19