ScrollView控件實現屏幕滾動

  滾動視圖是指當擁有很多內容,屏幕顯示不完全時,需要通過滾動來顯示完整的視圖

ScrollView的種類:

(1)水平滾動視圖:HorizontalScrollView

(2)垂直滾動視圖:ScrollView(我們默認的就是垂直滾動)

下面我們先來一個簡單的例子(在文字多的屏幕無法顯示的時候,把TextView控件嵌套在ScrollView裏面實現滾動視圖的效果):

佈局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    <ScrollView 
        android:id="@+id/scroll"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="@string/content" />
        
    </ScrollView>
    </RelativeLayout>
java代碼文件很簡單只需要引入佈局就行了(只要沒有創建新佈局,默認的就是)這裏就不多寫了。




隱藏ScrollView

(1) 標籤屬性:android:scrollbars="none"

(2) 代碼設置:

setHorizontalScrollBarEnabled(false);隱藏橫向ScrollView

setVerticalScrollBarEnabled(false);隱藏縱向ScrollView


setOnTouchListener的使用

判斷ScrollView何時滑動到底部

public class MainActivity extends Activity {
private TextView text;
private ScrollView scroll;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);

scroll = (ScrollView) findViewById(R.id.scroll);
scroll.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_UP:

break;


case MotionEvent.ACTION_DOWN:

break;
case MotionEvent.ACTION_MOVE:
/*
* (1)getScrollY()==滾動條滑動的距離
* (2)getMeasuredHeight()
* (3)getHeight()
* */
//頂部狀態
if (scroll.getScrollY() <= 0) {
Log.i("main", "已經到到了頂部");
}else if (scroll.getChildAt(0).getMeasuredHeight() <= scroll.getHeight() + scroll.getScrollY()) {
Log.i("main", "已經到了底部");

}
break;
}
return false;
}
});

}

}

那麼我們還可以在文字滑動到底部的時候,繼續加載文字,我們只需要加這樣一條代碼就可以了:

text.append(getResources().getString(R.string.content));

那麼我們還可以設定滾動的位置

我們需要在佈局中添加兩個按鈕"向上和向下",

然後在java代碼中添加點擊事件在點擊事件中加入這樣的兩個方法:

scroll.scrollBy(0, -30);

scroll.scrollBy(0, 30);

後面的那個數值爲正,則向下滾動,數值爲負,則向上滾動

代碼下載地址:http://download.csdn.net/detail/weimo1234/8438487

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