java - 以编程方式添加到自定义视图持有者的自定义视图实例的位置和大小错误
问题描述
我有一个自定义视图(扩展View
),一个自定义视图组(扩展LinearLayout
),它应该包含我的自定义视图的多个实例。初始化发生在Fragment
. 我想要实现的是让自定义视图实例在我的自定义视图组中水平排列(它应该最终成为一个多滑块)。到目前为止我所取得的成就:我可以将我的自定义视图实例添加到我的自定义视图组,但它们显示不正确 - 第一个实例(垂直条)显示正确,后续条既没有正确定位,也没有正确的宽度(见截图)。
从为我的自定义视图实例查询诸如getX()
, getWidth()
, getLeft()
,之类的值时,getRight()
我没有得到任何提示 - 报告的值表明滑块的布局和位置正确。
涉及 3 个自定义类:
片段
public class MultiSliderFragment extends MSBaseFragment {
private final static String TAG = "MultiSliderFragment";
private MultiSliderView mMSView;
public MultiSliderFragment() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mMSContainer = inflater.inflate(R.layout.multislider_view, container, false);
mMSView = (MultiSliderView) mMSContainer.findViewById(R.id.multislider_view);
Bundle numsBundle = this.getArguments();
ArrayList<Integer> sliderNums = numsBundle.getIntegerArrayList("nums");
ArrayList<SliderBar> sliders = new ArrayList<>();
assert sliderNums != null;
for (int num : sliderNums) {
SliderBar bar = new SliderBar(getActivity());
bar.setNum(String.valueOf(num));
sliders.add(bar);
}
int x = 0;
for (SliderBar slider : sliders) {
mMSViewLeft.addView(slider);
}
// sliders have to know their number
// and the container view (MultiSliderView)
// needs know the dimensions of the screen
setSliderProps(sliderNums);
return mMSContainer;
}
private void setSliderProps(ArrayList<Integer> sliderNums) {
MSApplication app = (MSApplication) getActivity().getApplication();
Point screenDimensions = app.getDimensions();
mMSView.setScreenDimensions(screenDimensions);
mMSView.setSliderNums(sliderNums);
}
}
持有滑块的 ViewGroup
public class MultiSliderView extends LinearLayout {
final static private String TAG = "MultiSliderView";
private ArrayList<Integer> sliderNums;
private Point screenDimensions;
public MultiSliderView(Context context) {
super(context);
init(null, 0);
}
public MultiSliderView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public MultiSliderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr);
}
private void init(AttributeSet attrs, int defStyleAttr) {
this.setOrientation(LinearLayout.HORIZONTAL);
}
public void setSliderNums(ArrayList<Integer> sliderNums) {
this.sliderNums = sliderNums;
}
public void setScreenDimensions(Point dimensions) {
this.screenDimensions = dimensions;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int desiredWidth = getSuggestedMinimumWidth() + getPaddingLeft() + getPaddingRight();
int desiredHeight = getSuggestedMinimumHeight() + getPaddingTop() + getPaddingBottom();
int measureWidth = measureDimension(desiredWidth, widthMeasureSpec);
int measureHeight = measureDimension(desiredHeight, heightMeasureSpec);
setMeasuredDimension(measureWidth, measureHeight);
}
private int measureDimension(int desiredSize, int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = desiredSize;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
if (result < desiredSize) {
Log.e(TAG, "The view is too small, the content might get cut");
}
return result;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Log.d(TAG, "MultiSliderView on layout: " + left + ", " + top + ", " + right + ", " + bottom);
int barWidth = getMeasuredWidth()/sliderNums.size();
int barHeight = getMeasuredHeight();
int x = 0;
for (int i = 0; i < getChildCount(); i++) {
SliderBar child = (SliderBar) getChildAt(i);
child.layout(x, 0, x + barWidth, barHeight);
// increment x by barWidth, otherwise bars are laid out
// on top of each other, each at position 0 within MultiSliderView
x += barWidth;
}
}
// manual interaction with the multislider (stub)
// must report to the regarding SliderBar instance to redraw the slider
@Override
public boolean onTouchEvent(MotionEvent event) {
performClick();
this.getParent().requestDisallowInterceptTouchEvent(true);
int tempTouchX = (int) event.getX();
int tempTouchY = (int) event.getY();
Log.d(TAG, "touch position: " + tempTouchX + ", " + tempTouchY);
invalidate();
return true;
}
@Override
public boolean performClick() {
super.performClick();
return false;
}
滑动条
public class SliderBar extends View {
final static String TAG = "SliderBar";
Paint mPaint;
Canvas mCanvas;
String pixelNum;
Typeface typeFace = Typeface.create("sans-serif-light", Typeface.NORMAL);
int left, top, right, bottom;
Rect mArea = new Rect(left, top, right, bottom);
int touchY;
public SliderBar(Context context) {
super(context);
init(null, 0);
}
public SliderBar(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public SliderBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCanvas = new Canvas();
}
@Override
protected void onDraw(Canvas canvas) {
Log.d(TAG, "slider bar on draw: " + left + ", " + top + ", " + right + ", " + bottom);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(0x66000000);
if (touchY <= top) touchY = top;
if (touchY > bottom) touchY = bottom;
canvas.drawRect(left, touchY, right, bottom, mPaint);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTypeface(typeFace);
mPaint.setTextSize((float) 30);
mPaint.setColor(0xffffffff);
canvas.drawText(pixelNum, right/2, bottom - 20, mPaint);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
this.setLeft(left);
this.setTop(top);
this.setRight(right);
this.setBottom(bottom);
// reports the right values but sliders aren't positioned correctly
Log.d(TAG, "slider position: " + this.getLeft() + ", " + this.getRight());
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public void setNum(String num) {
this.pixelNum = num;
}
}
最后但同样重要的是:包含 MultiSliderView 的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/multislider_view"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:baselineAligned="false">
<net.myapp.views.MultiSliderView
android:id="@+id/multislider_view_left"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:layout_marginEnd="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:background="@android:color/holo_blue_dark"
android:orientation="horizontal"/>
</LinearLayout>
我认为MultiSliderView
继承自LinearLayout
将允许我将滑动条放置在水平行中,即使没有给它们一个水平位置。但是,情况并非如此——只需将它们的 x 位置设置为 0,只需将它们在位置 0 处相互重叠放置。在定位滑块时我是否有明显的错误?
谢谢
解决方案
这是我使用您的代码并在某些地方对其进行修补的结果(Application
类中的 getDimension() 将返回当前使用的widthPixels和heightPixels):Window
DisplayMetrics
到目前为止我的变化:
1有时我会收到一个 NPE onLayout()
,MultiSliderView
因为在传入View
数字之前它已经启动并运行ArrayList
。所以我添加了一个null
check inonLayout()
以及invalidate();
最后一行setSliderNums()
2 s的SliderBar
位置似乎很好(使用 LayoutInspector 检查),但大多数数字不可见。我想它们应该出现在它们的中间SliderBar
(如果我错了,请跳过这一点)。
您绘制数字的代码:
canvas.drawText(pixelNum, right/2, bottom - 20, mPaint);
这不起作用,因为 left、top 等的值是相对于 parent 的,但是您在相对于 childViewGroup
的 in 坐标上绘制。所以我把这条线改成Canvas
View
canvas.drawText(pixelNum, (right - left)/2, bottom - 20, mPaint);
3同样,它似乎setX()
不像您期望的那样工作(“简单地将它们的 x 位置设置为 0,只是将它们在位置 0 处相互重叠放置”),所以让我试着解释一下它的作用:
setX()
与和一起使用的值setY()
是相对于ViewGroup
包含有View
问题的父级的。因此,如果您说view.setX(0);
,View
将在其父级的左边缘绘制ViewGroup
。
4在onLayout()
其中SliderBar
,没有必要通过调用等来设置left、top、...this.setLeft(left);
值。在这个方法中,View
通知已经对这些变量进行了更改。所以我跳过了四个多余的行。
5我不太明白的是你试图通过以下两行从onDraw()
in 中实现的目标SliderBar
:
if (touchY <= top) touchY = top;
if (touchY > bottom) touchY = bottom;
基本上,他们所做的只是将touchY的值设置为底部,如果touchY > bottom
在开始时(假设 top > bottom
),并且在开始时将touchY单独touchY <= bottom
放置。
现在的情况是,在大多数情况下,生成的矩形是相当一维的。
所以我想知道此时应该发生什么。
推荐阅读
- ios - Swift:重构 NSMutableAttributedString
- zk - 如何使用动态文本框创建通信
- mule - Mule 是否支持键中的“-”(连字符)?
- javascript - 带有 JQuery 事件的条码阅读器
- ios - 当我使用 UIDocumentPickerViewController 从 iCloud 中选择 zip 文件时无法与帮助应用程序通信
- google-cloud-platform - BigQuery 命令“bq mk”引发错误“mk 操作中的 BigQuery 错误:读取架构时出错:”
- mysql - 如何使用 linq2db 将聚合映射到单个表
- java - 如何在 avro java 项目中处理具有不同数据库名称的多个部署环境?
- uicollectionviewcell - 需要固定大小的收集单元
- php - 从现有表生成实体