我正在尝试使用函数View::scrollBy(int, int)
在自定义视图中滚动LinearLayout
。问题是,当LinearLayout
中添加的视图的高度为WRAP_CONTENT
时,滚动时会剪切内容。但是,当视图具有固定高度(例如20px)时,不会发生此问题。我想使用固定高度的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评论此related question中的解决方法。但我不喜欢它的附带问题。