问题:当我添加两个TextView的时候,然后滑动,发现只生成了一个TextView。
就是
<?xml version="1.0" encoding="utf-8"?> <com.maikefengchao.viewcompflict.HorzonScrollLinearLayout 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" android:orientation="horizontal" tools:context="com.maikefengchao.viewcompflict.MainActivity"> <TextView android:id="@+id/main_tv_first" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/holo_blue_light" android:text="我是第一页" android:gravity="center"/> <TextView android:id="@+id/main_tv_second" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/darker_gray" android:text="第二页" android:gravity="center"/> </com.maikefengchao.viewcompflict.HorzonScrollLinearLayout>
activity_main
public class HorzonScrollLinearLayout extends LinearLayout { private int mLastX; private int mLastY; private int mCurrentX; private int mCurrentY; private int mTouchLastX; private int mTouchLastY; public HorzonScrollLinearLayout(Context context) { super(context); } public HorzonScrollLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public HorzonScrollLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onTouchEvent(MotionEvent event) { int scrollX = (int) event.getX(); int scrollY = (int) event.getY(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: int deltaX = mLastX - scrollX; scrollBy(deltaX,0); break; case MotionEvent.ACTION_UP: break; } mLastX = scrollX; mLastY = scrollY; return true; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { boolean isIntercept = false; mCurrentX = (int) ev.getX(); mCurrentY = (int) ev.getY(); switch (ev.getAction()){ case MotionEvent.ACTION_DOWN: isIntercept = false; break; case MotionEvent.ACTION_MOVE: //往左滑动为正 int deltaX = mLastX - mCurrentX; int deltaY = mLastY - mCurrentY; if(Math.abs(deltaX) > Math.abs(deltaY)){ isIntercept = true; } else { isIntercept = false; } break; case MotionEvent.ACTION_UP: isIntercept = false; break; } mLastX = mCurrentX; mLastY = mCurrentY; return isIntercept; }
HorzonScrollLinearLayout
发生滑动的时候,只有第一个显示出来
为什么会这样子呢,因为我忘了LinearLayout的大小是屏幕的宽度,所以整体大小值有一个屏幕宽,第二个TextView因为第一个TextView占满的屏幕,根据LinearLayout的源码
就是当前容器的宽度大小 减去 上一子类View占用的控件,就是当前子类的可用空间。
解决办法:
1、在java文件中,将TextView加入LinearLayout中,并设置TextView的LayoutParam.width 为 屏幕宽度。
TextView textView = new TextView(this); textView.getLayoutParams().width = screenWidth; textView.getLayoutParams().height = screenHeight; mHorzonScroll.addView(textView);
解决办法
时间: 2024-11-05 23:18:40