如何将Fab按钮的位置设置为Android

时间:2017-08-29 18:01:19

标签: android android-layout floating-action-button

我正在使用此代码:

fabButton.setOnTouchListener(new View.OnTouchListener() {

    float x, y;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){

            case MotionEvent.ACTION_MOVE:

                fabButton.setX(fabButton.getX() + (event.getX() - x));
                fabButton.setY(fabButton.getY() + (event.getY() - y));
                return true;
            case MotionEvent.ACTION_DOWN:
                x = event.getX();
                y = event.getY();
                return true;
        }

        return false;
    }
});

现在我想将Fab按钮的位置设置为协调器布局的最右边或最左边。

可能是

if (xCoordinate < screen center)
{
   align Fab  button to the Right screen
}

if (xCoordinate > Screen Center)
{
   align Fab button to the left of the screen
}

我不知道如何管理这件事。

3 个答案:

答案 0 :(得分:0)

试试这个:----

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams params= (CoordinatorLayout.LayoutParams) 
fab.getLayoutParams();
params.anchorGravity = Gravity.BOTTOM | GravityCompat.START;
fab.setLayoutParams(params/);

根据需要设置开始,结束,顶部,底部。

答案 1 :(得分:0)

CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)  
floatingbutton.getLayoutParams();
lp.gravity = Gravity.CENTER_HORIZONTAL; 
/// or any other place you want like 

答案 2 :(得分:0)

我设法做到这一点,现在正确地将Fab Button定位为左或右

Display display = getWindowManager().getDefaultDisplay();
                    Point size = new Point();
                    display.getSize(size);
                    CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
                    p.setBehavior(new FloatingActionButton.Behavior());
                    fab.setLayoutParams(p);
                    if(fab.getX() < 0)
                    {
                        fab.setX(2.0f);
                    }
                    if(fab.getX() > size.x)
                    {
                        fab.setX(size.x -1);
                    }

                    if(fab.getY() < 0)
                    {
                        fab.setY(4.0f);
                    }
                    if(fab.getY() > size.y)
                    {
                        fab.setY(size.y -1);
                    }

                    if(fab.getX() < size.x/2)
                    {
                        fab.setX((5*size.x/100));
                    }else
                    {
                        fab.setX(size.x - (12*size.x/100));
                    }

它的工作