3

我正在尝试使用该功能在自定义视图View::scrollBy(int, int)中滚动 a LinearLayout。问题是,当在其中添加的视图高度时,LinearLayout内容WRAP_CONTENT在滚动时被剪裁。但是,当视图具有固定高度(例如 20 像素)时,不会发生此问题。我想使用WRAP_CONTENT固定高度的 instade。我怎样才能做到这一点?

我写了这个简单的代码来重现这个问题。您可以在此图像中看到问题:

剪裁线性布局

编码:

public class Scroll extends LinearLayout {
    private final Context context;

    private int currentY;

    public Scroll(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;

        LayoutInflater.from(context).inflate(R.layout.scroll, this, true);

        LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutParams params2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 19);

        fillRow((LinearLayout) findViewById(R.id.ll1), params1);
        fillRow((LinearLayout) findViewById(R.id.ll2), params2);
    }

    private void fillRow(LinearLayout linearLayout, LinearLayout.LayoutParams layoutParams) {
        for (int i = 0; i < 100; i++) {
            TextView textView = new TextView(context);
            textView.setBackgroundResource(android.R.color.white);
            textView.setLayoutParams(layoutParams);
            textView.setText(i + "");
            linearLayout.addView(textView);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Idea: https://stackoverflow.com/a/4991692/842697
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                currentY = (int) event.getRawY();
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                int y2 = (int) event.getRawY();
                int scrollY = currentY - y2;
                currentY = y2;

                findViewById(R.id.ll1).scrollBy(0, scrollY);
                findViewById(R.id.ll2).scrollBy(0, scrollY);

                break;
            }
            case MotionEvent.ACTION_UP: {
                break;
            }
        }
        return true;
    }
}

R.layout.scroll这个 XML在哪里:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/ll1"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#FF0000"
        android:orientation="vertical" />

    <LinearLayout
        android:id="@+id/ll2"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#00FF00"
        android:orientation="vertical" />

</LinearLayout>

@Anne Droid在这个相关问题中评论了一个解决方法。但我不喜欢它的附带问题。

4

0 回答 0