HorizontalScrollView
別の方法として、 a の代わりにカスタムを使用し、ViewPager
そのメソッドを上書きしonTouchEvent
て、次のように ViewPager で得られるのと同じスナップ効果を得ることができます。
public class MyHorizontalScrollView extends HorizontalScrollView {
public MyHorizontalScrollView(Context context) {
super(context);
}
public MyHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_UP:
if (mScrollable) {
View child = getChildAt(0);
if (child != null) {
final int currentX = getScrollX();
final int windowWidth = getResources().getDisplayMetrics().widthPixels;
final int totalWidth = child.getWidth();
int showingElementNumber = 1;
int i = windowWidth;
while (i < currentX && i < totalWidth) {
i+=windowWidth;
showingElementNumber++;
}
int scrollTo = 0;
if (currentX < (windowWidth * (showingElementNumber - 1) + windowWidth/2)) { // Previouses widths + half the current
scrollTo = windowWidth * (showingElementNumber - 1);
} else {
scrollTo = windowWidth * showingElementNumber + marginSize;
}
smoothScrollTo(scrollTo, 0);
return false;
}
}
return super.onTouchEvent(ev);
default:
return super.onTouchEvent(ev);
}
}
}
次に、その中に2つ追加Fragments
し、通常のFragmentTransaction
withを使用して、addToBackStack()
必要なものを取得できます。
注:上記のコードを使用する場合は、フラグメントが画面全体と同じ幅であることを確認してください。構造は次のようにする必要があります。
MyHorizontalScrollView > LinearLayout > YourFragment1
> YourFragment2