android ScrollView滾動到底部

只做記錄,方便日後再遇到相似的問題可以回顧


下面是佈局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity">

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button
            android:text="start"
            android:id="@+id/start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        </FrameLayout>

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:id="@+id/output "
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
        </ScrollView>

</LinearLayout>

點擊Button,就讓滾動條滾到最下方

    private TextView outputTextView = null;
    private Button startButton = null;
    private ScrollView scrollView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        initView();
    }

    private void initView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                startButton = (Button)findViewById(R.id.start);
                startButton.setOnClickListener(onClickListener);


                outputTextView = (TextView)findViewById(R.id.output);
                scrollView = (ScrollView)findViewById(R.id.scrollView);
                for (int i = 0 ; i < 1000 ; i ++ ) {
                    Message msg = new Message();
                    msg.what = HANDLER_APPEND_OUTP0UT;
                    msg.obj = i + " ";
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch(v.getId()) {
                case R.id.start:
                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    break;
            }
        }
    };


    private static final int HANDLER_APPEND_OUTP0UT = 0 ;
    private Handler handler  = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case HANDLER_APPEND_OUTP0UT:
                    outputTextView.append((String) msg.obj);
                    break;
            }
        }
    };









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章