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

后端 未结 2 1339
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 22:55

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 fr

2条回答
  •  孤城傲影
    2020-12-10 23:42

    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.

提交回复
热议问题