【发布时间】:2018-12-02 08:19:56
【问题描述】:
我正在开发一个有自定义视图的 android 项目。单击自定义视图时,我希望在视图的每个角落放置一个视图(一个圆圈)。
目前我只是想让它在左上角工作,但它最终在中间。
下面是我添加视图的点击功能。
View view = LayoutInflater.from(getContext()).inflate(R.layout.view, this, false);
TextView textItem = view.findViewById(R.id.lblItemText);
textItem.setText("View: " + counter);
view.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Anchor anchor1 = new Anchor(getContext());
anchor1.setLeft(v.getLeft());
anchor1.setTop(CustomView.this.getTop());
CustomView.this.addView(anchor1);
}
});
自定义视图托管在相对布局中。自定义视图扩展了 RelativeLayout,并且应该进入自定义视图左上角的锚视图扩展了按钮。
锚构造函数包含以下内容:
public Anchor(Context context)
{
super(context);
this.setBackgroundResource(R.drawable.anchor);
this.setPadding(0,0,0,0);
this.setWidth(1);
this.setHeight(1);
}
由于某种原因,锚点出现在中间而不是如下所示的角落
下面有点期待。
更新
几天后取得了一些进展,我确实让它工作了,除了它使用硬编码值将它放在正确的位置,这似乎不正确。我猜这仅适用于我正在测试的特定设备,另一台具有其他分辨率的设备将定位错误。
下面是我拥有的代码,希望能显示我想要实现的目标以及我现在拥有的屏幕截图。
private void createAnchorPoints()
{
//Main View
ViewGroup mainView = activity.findViewById(android.R.id.content);
int[] viewToBeResizedLoc = new int[2];
viewToBeResized.getLocationOnScreen(viewToBeResizedLoc);
//Add top left anchor
Anchor topLeftAnchor = new Anchor(context, Anchor.ResizeMode.TOP_LEFT);
FrameLayout.LayoutParams topLeftParms = new FrameLayout.LayoutParams(150,150);
topLeftParms.leftMargin = viewToBeResizedLoc[0] - 50;
topLeftParms.topMargin = viewToBeResizedLoc[1] - viewToBeResized.getHeight() - 30;
topLeftAnchor.setLayoutParams(topLeftParms);
mainView.addView(topLeftAnchor);
//Add top right anchor
Anchor topRightAnchor = new Anchor(context, Anchor.ResizeMode.TOP_RIGHT);
FrameLayout.LayoutParams topRightParms = new FrameLayout.LayoutParams(150, 150);
topRightParms.leftMargin = topLeftParms.leftMargin + viewToBeResized.getWidth() - 40;
topRightParms.topMargin = topLeftParms.topMargin;
topRightAnchor.setLayoutParams(topRightParms);
mainView.addView(topRightAnchor);
//Add bottom left anchor
Anchor bottomLeftAnchor = new Anchor(context, Anchor.ResizeMode.BOTTOM_LEFT);
FrameLayout.LayoutParams bottomLeftParms = new FrameLayout.LayoutParams(150, 150);
bottomLeftParms.leftMargin = topLeftParms.leftMargin;
bottomLeftParms.topMargin = topLeftParms.topMargin + viewToBeResized.getHeight() - 40;
bottomLeftAnchor.setLayoutParams(bottomLeftParms);
mainView.addView(bottomLeftAnchor);
//Add bottom right anchor
Anchor bottomRightAnchor = new Anchor(context, Anchor.ResizeMode.BOTTOM_RIGHT);
FrameLayout.LayoutParams bottomRightParms = new FrameLayout.LayoutParams(150, 150);
bottomRightParms.leftMargin = topRightParms.leftMargin;
bottomRightParms.topMargin = bottomLeftParms.topMargin;
bottomRightAnchor.setLayoutParams(bottomRightParms);
mainView.addView(bottomRightAnchor);
}
【问题讨论】:
-
getLeft(),getTop()等返回视图相对于其父视图的坐标,即坐标系被“移位”。很可能您应该知道视图相对于根视图的坐标并进行计算 w.t.r.一点额外的解释是here
标签: android