【发布时间】:2013-11-28 22:23:05
【问题描述】:
public class Game_collecting_view extends View
{
Button image_boy;
private static final int BOY_DIAMETER = 200; // initial spot size
int boy_width =0;
int boy_height =0;
public void setGame_collecting(Game_collecting mGame_collecting)
{
this.mGame_collecting = mGame_collecting;
}
// constructs a new View
public Game_collecting_view(Context context, RelativeLayout parentLayout)
{
super(context);
resources = context.getResources(); // save Resources for loading external values
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// get references to various GUI components
relativeLayout = parentLayout;
spotHandler = new Handler(); // used to add spots when game starts
}
@Override
protected void onSizeChanged(int width, int height, int oldw, int oldh)
{
viewWidth = width; // save the new width
viewHeight = height; // save the new height
}
public void set_boy()
{
final Button boy = (Button) layoutInflater.inflate(R.layout.untouched, null);
boy.setX(viewWidth /2);
boy.setY(viewHeight - BOY_DIAMETER);
boy.setPadding(0,0,0,0);
boy.setBackgroundResource(R.drawable.blue);
boy.setLayoutParams(new RelativeLayout.LayoutParams(BOY_DIAMETER, BOY_DIAMETER));
relativeLayout.addView(boy); // add spot to the screen
Toast.makeText(getContext(), "set_boy\nviewWidth=" +viewHeight +"\nviewHeight=" +viewHeight, Toast.LENGTH_SHORT).show();
boy.setOnClickListener
(
new OnClickListener()
{
public void onClick(View v)
{
touchedSpot(boy);
}
}
);
}
public void resume(Context context)
{
resetGame();
}
public void resetGame()
{
for (int i = 1; i <= INITIAL_SPOTS; ++i)
{
spotHandler.postDelayed(addSpotRunnable, i * SPOT_DELAY);
generate_text();
}
set_boy();
}
private Runnable addSpotRunnable = new Runnable()
{
public void run()
{
addNewSpot(); // add a new spot to the game
}
};
目标:
我想在屏幕底部中间设置男孩图标。 男孩图标就是这样设置的,以后的动态界面(向右滑动屏幕男孩图标会向右移动,反之亦然)
观察:
toast 报告 viewWidth 和 viewHeight =0,男孩图标出现在 0,0(左上角)。如果我设置 setY(viewHeight + BOY_DIAMETER),男孩图标将位于 (0, 200)。
问题:
我想问一下为什么viewWidth和viewHeight都报0。如何立即调用onSizeChanged使得男孩图标可以设置在屏幕的底部中心?
谢谢!!
【问题讨论】:
-
stackoverflow.com/questions/19932253/… 在这里查看我的答案
-
您在元素布局在屏幕上之前太早询问尺寸。
-
@njzk2:你说得对,我现在使用
getViewTreeObserver()来推导ViewWidth和ViewHeight,然后再通过setX和setY。然而男孩图标仍然位于 (0,0)。我试过如果使用setX(720/2)和setY(1134-200)它可能位于所需的位置。这意味着在设置男孩图标之前尚未收到viewWidth和viewHeight....那样我怎么能推迟定位男孩图标? usingHandler如何知道何时检索到维度?
标签: android view android-relativelayout coordinate