Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

android - How to place views in a specific location (x, y coordinates)

I have a problem with placing my views (my class extends View) in a specific location. I have designed a game that treats the screen as a net of grids. I get from the user x and y coordinates of a specific view (I have different types of views).

My first mission is to set the correct view in its place. How can I do it? I am using RelativeLayout for the screen.

P.S. I don't want to use AbsoluteLayout params because it was truncated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not the best way to achieve it, but it's a solution...

Create a class that extends your parent ViewGroup, say RelativeLayout or some other ViewGroups. Find your own view in overriding onFinishInflate().

Override the onLayout() method and manually layout your own view after calling super.onLayout().

Finally, every time you want to refresh the location of your own view, just call requestLayout().

Here is a sample below:

private AwesomeView mMyView;
private int mYourDesiredX;
private int mYourDesiredY;

@Override
public void onFinishInflate() {
    super.onFinishInflate();
    if (mMyView == null) {
        mMyView = (AwesomeView)findViewById();
    }
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    mMyView.layout(mYourDesiredX,
            mYourDesiredY,
            mYourDesiredX + mMyView.getWidth(),
            mYourDesiredY + mMyView.getHeight());
}

But this is not an efficient solution.

If you are making games, try SurfaceView or even GLSurfaceView and draw the objects by your own with Canvas.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...