Android开发之ListView+EditText-要命的焦点和软键盘问题解决办法

本文介绍了一个在 ListView 中使用 EditText 的实现方案,通过自定义 getView 方法实现了 EditText 的重用,确保了良好的用户体验并详细解释了如何处理触摸事件及文本变化监听。

//这个是设置EditText添加到行的Layout时需要的属性,高度无所谓,宽度要填满父容器,别手动设置宽度dp

private LayoutParams fillParentLayoutParams = new LinearLayout.LayoutParams(

        LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);

private int index = -1;


public View getView(final int position, View convertView, ViewGroup parent) {

        // 这个地方就是决定convertView是否重用的,一定要判断!

        if(convertView == null) {

                convertView = new LinearLayout(activity);
        }

        else{

                // 因为项目中每一行的控件究竟有什么都不确定,所以清掉layout里的所有控件,你的项目视情况而定。

                ((LinearLayout) convertView).removeAllViews(); 

        }

        // 不要直接new一个Layout去赋值给convertView!!那样就不是重用了,否则,后果自负~~


        EditText editText = new EditText(activity);

        // 你可以试试把addView放到这个函数的return之前,我保证你会后悔的~~

       // 因为前面说过,addView的先后对画面的结果是有影响的。

        ((LinearLayout) convertView).addView(editText, fillParentLayoutParams);


        editText.setOnTouchListener(new OnTouchListener() {

                public boolean onTouch(View view, MotionEvent event) {

                        // 在TOUCH的UP事件中,要保存当前的行下标,因为弹出软键盘后,整个画面会被重画

                        // 在getView方法的最后,要根据index和当前的行下标手动为EditText设置焦点 

                        if(event.getAction() == MotionEvent.ACTION_UP) {

                                index= position;

                        }

                        return false;

                }

        });

        

        editText.addTextChangedListener(new TextWatcher(){

                public void afterTextChanged(Editable editable) {

                }

                public void beforeTextChanged(CharSequence text, int start, int count, int after) {

                }

                public void onTextChanged(CharSequence text, int start, int before, int count) {

                        // 在这个地方添加你的保存文本内容的代码,如果不保存,你就等着重新输入吧

                        // 而且不管你输入多少次,也不会有用的,因为getView全清了~~

                }

        });


        // 这个地方可以添加将保存的文本内容设置到EditText上的代码,会有用的~~


        editText.clearFocus();

        if(index!= -1 && index == position) {

               // 如果当前的行下标和点击事件中保存的index一致,手动为EditText设置焦点。

                editText.requestFocus();

        }


       // 这个时候返回的东东,就是ListView对应行下标的那一行的内容。

        return convertView;

}

转载于:https://my.oschina.net/yolinfeng/blog/384571

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值