在android中的特定字段后ScrollView自动滚动

时间:2014-06-24 10:59:47

标签: android scrollview

此代码可以帮助我自动滚动点击功能,但是当点击编辑文本4时,它只向上滚动一个字段。我希望该字段转到屏幕顶部。我使用向上滚动,滚动,滚动到,除了所有之外的所有内容都给出相同的结果。你能帮忙吗?


package com.example.scrollview;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ScrollView;


public class MainActivity extends Activity{
EditText edtText4,edtText8;
ScrollView scrollView;
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    scrollView = (ScrollView)findViewById(R.id.scv);

    edtText4 = (EditText)findViewById(R.id.editText4);
    edtText8 = (EditText)findViewById(R.id.editText8);  

    edtText4.setOnTouchListener(selectedFieldTouchListener);
    edtText8.setOnTouchListener(selectedFieldTouchListener);

}
private OnTouchListener selectedFieldTouchListener = new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int top1 = 0;
        switch (v.getId()) {
        case R.id.editText4:
            top1 = edtText4.getTop();  
            break;
        case R.id.editText8:
            top1 = edtText8.getTop();
            break;
        }
        final int top = top1;
        scrollView.postDelayed(new Runnable() {//must be in postDelayed otherwise wont work

            @Override
            public void run() {
                scrollView.scrollTo(0, edtText4.getTop());
            }
        }, 100);

        return false;
    }
};

}


1 个答案:

答案 0 :(得分:1)

这假设EditTextsScrollView

的直接子女
private OnTouchListener selectedFieldTouchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int top1 = 0;
            switch (v.getId()) {
            case R.id.editText4:
                top1 = edtText4.getTop();
                break;
            case R.id.editText8:
                top1 = edtText8.getTop();
                break;
            }
            final int top = top1;
            scrollView.postDelayed(new Runnable() {//must be in postDelayed otherwise wont work

                @Override
                public void run() {

                    scrollView.scrollTo(0, top);
                }
            }, 100);

            return false;
        }
    };

然后将Touch Listener添加到您的EditTexts

    edtText4.setOnTouchListener(selectedFieldTouchListener);
    edtText8.setOnTouchListener(selectedFieldTouchListener);