首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android HorizontalScrollView 兩側箭頭指示器:自訂 View 監聽滾動狀態顯示隱藏

     編輯:程式設計綜合問答

繼承 HorizontalScrollView 並實作介面回調滾動極值,主程式根據回調控制左右箭頭圖片的可見性。

自訂 HorizontalScrollView

public class ExtendedHorizontalScrollView extends HorizontalScrollView {
    public interface OnScrollEdgeListener {
        void onScrollMostLeft();
        void onScrollFromMostLeft();
        void onScrollMostRight();
        void onScrollFromMostRight();
    }
    private OnScrollEdgeListener listener;

    public ExtendedHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (listener == null) return;
        View content = getChildAt(0);
        if (content == null) return;

        if (l == 0) listener.onScrollMostLeft();
        else if (oldl == 0) listener.onScrollFromMostLeft();

        int maxScroll = content.getWidth() - getWidth();
        if (l >= maxScroll) listener.onScrollMostRight();
        else if (oldl >= maxScroll) listener.onScrollFromMostRight();
    }

    public void setOnScrollEdgeListener(OnScrollEdgeListener l) { listener = l; }
}

佈局 XML

<LinearLayout android:orientation="horizontal" ...>
    <ImageView android:id="@+id/leftArrow" android:src="@drawable/ic_left" android:visibility="gone"/>
    <com.example.ExtendedHorizontalScrollView
        android:id="@+id/scroller"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent">
        <LinearLayout android:id="@+id/content" android:orientation="horizontal" ... />
    </com.example.ExtendedHorizontalScrollView>
    <ImageView android:id="@+id/rightArrow" android:src="@drawable/ic_right" android:visibility="gone"/>
</LinearLayout>

主程式綁定

ExtendedHorizontalScrollView scroller = findViewById(R.id.scroller);
ImageView left = findViewById(R.id.leftArrow), right = findViewById(R.id.rightArrow);
scroller.setOnScrollEdgeListener(new ExtendedHorizontalScrollView.OnScrollEdgeListener() {
    @Override public void onScrollMostLeft() { left.setVisibility(View.GONE); }
    @Override public void onScrollFromMostLeft() { left.setVisibility(View.VISIBLE); }
    @Override public void onScrollMostRight() { right.setVisibility(View.GONE); }
    @Override public void onScrollFromMostRight() { right.setVisibility(View.VISIBLE); }
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved