我正在用 Android 开发我的第一款游戏。在游戏的一部分中,我正在绘制一条路径,我希望该路径从 RelativeLayout
的中心开始。我已成功获取中心坐标,但现在我需要将这些坐标 (int xCenterInt, yCenterInt;
) 传递到我的自定义 View ,而这正是我无法弄清楚的。我无法让 Intents 工作,除非我做错了 Intents。那么如何将我的 int 值传递到我的自定义 View 类中呢?这是我在主 Activity 中使用的获取中心坐标的方法:
public void getBoardNumbers() {
gBoard_RL.getViewTreeObserver().addOnGlobalLayoutListener(NumbersoGLL);
}
OnGlobalLayoutListener NumbersoGLL = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
xScrInt = gBoard_RL.getWidth();
yScrInt = gBoard_RL.getHeight();
xScr2Int = gBoard_RL.getWidth() / 2;
yScr2Int = gBoard_RL.getHeight() / 2;
xCenterInt = gBoard_RL.getLeft() + xScr2Int;
yCenterInt = gBoard_RL.getTop() + yScr2Int;
//---- How do I get xCenterInt, yCenterInt to my DrawPath Class?
}
};
这是我的自定义 View 类,需要在其中插入坐标:
public class DrawPath extends View {
Paint paint = new Paint();
Path path = new Path();
int xC_Int, yC_Int;
//--- The coordinates Integers need to go here:
Pt[] thePath = { new Pt(xC_Int, yC_Int),
new Pt(200, 200),
new Pt(200, 500),
new Pt(400, 500) };
public DrawPath(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.RED);
paint.setStrokeWidth(7);
paint.setStyle(Paint.Style.STROKE);
path.moveTo(thePath[0].x, thePath[0].y);
for (int i = 1; i < thePath.length; i++) {
path.lineTo(thePath[i].x, thePath[i].y);
}
canvas.drawPath(path, paint);
}// --- END onDraw
class Pt {
float x, y;
Pt(float _x, float _y){
x = _x;
y = _y;
}
}//--- END PT
}
最佳答案
您可以通过在 DrawPath
类中为 xCenterInt
和 yCenterInt
创建一个 setter - getter 来实现这一点,示例:
public class DrawPath extends View {
Paint paint = new Paint();
Path path = new Path();
int xC_Int, yC_Int;
int xCenterInt, yCenterInt; //create new variables
//your other codes
public void setxCenterInt(int setxCenterInt) {
this.setxCenterInt = setxCenterInt;
}
public int getxCenterInt() {
return setxCenterInt;
}
//do the same for yCenterInt
之后,使用我们之前创建的setter-getter:
OnGlobalLayoutListener NumbersoGLL = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
xScrInt = gBoard_RL.getWidth();
yScrInt = gBoard_RL.getHeight();
xScr2Int = gBoard_RL.getWidth() / 2;
yScr2Int = gBoard_RL.getHeight() / 2;
xCenterInt = gBoard_RL.getLeft() + xScr2Int;
yCenterInt = gBoard_RL.getTop() + yScr2Int;
//use your DrawPath instance
myDrawPathInstance.setxCenterInt(xCenterInt);
//do the same for yCenterInt
}
};
关于Android:将数据传递到自定义 View 类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26763256/