设置敬酒的动态位置视图(Set Dynamic position of Toast to a Vie

2019-08-07 19:30发布

首先,这是不完整的代码

@Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
    {
        Toast toast=Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0); 
        View view=toast.getView();
        switch(buttonView.getId())
        {
            case R.id.chkRed: if(chkRed.isChecked())
            {   
                              chkGreen.setChecked(false);
                              chkBlue.setChecked(false);
                              chkYellow.setChecked(false);
                              toast.setText("You Selected Red");
                                toast.setGravity(Gravity.NO_GRAVITY,buttonView.getRight(), chkRed.getTop());
                             //top does not align
                             //it align perfectly to right of checkbox
                              view.setBackgroundColor(Color.RED);
            }
                             break;
}
}

所以,现在的问题是,我想显示旁边的复选框敬酒,我试图与工作setGravity()但它只是不加工及受到的冲击,并试图使用很长时间,但没有取得进展

如何显示旁边的复选敬酒。

Answer 1:

好吧,我终于想通了如何获取复选框或其他视图旁边烤面包

1.您需要在视图的屏幕获得位置,由

buttonView.getLocationOnScreen(location);

更多的参考,参见getLocationOnScreen(INT [])

2.使用设置重力烤面包

toast.setGravity(Gravity.TOP|Gravity.LEFT,buttonView.getRight()+5, 
location[1]-10);

这里最重要的是设置x-coordinate敬酒来的观点正确,例如, buttonView.getRight()并从y坐标location[1]你从得到getLocationOnScreen()

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
    {
        Toast toast=Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0); 
        View view=toast.getView();
        int location[]=new int[2];
        buttonView.getLocationOnScreen(location);
        switch(buttonView.getId())
        {
            case R.id.chkRed: if(chkRed.isChecked())
            {   
                              chkGreen.setChecked(false);
                              chkBlue.setChecked(false);
                              chkYellow.setChecked(false);
                              toast.setText("You Selected Red");
                              toast.setGravity(Gravity.TOP|Gravity.LEFT,buttonView.getRight()+5, location[1]-10);
                              view.setPadding(1, 1, 1, 1);
                              view.setBackgroundColor(Color.RED);
            }

        }
    }


文章来源: Set Dynamic position of Toast to a View