如何将Toast的动态位置设置为一个视图?

8

首先,这不是完整的代码。

@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;
}
}

现在的问题是我想在复选框旁边显示toast,我尝试使用setGravity(),但它并没有起作用,已经试了很长时间,但没有进展。

如何在复选框旁边显示toast?

1个回答

10

好的,我最终弄清楚了如何将 Toast 放在复选框或另一个视图旁边。

1. 您需要获取视图在屏幕上的位置,方法是

buttonView.getLocationOnScreen(location);

了解更多信息,请参见getLocationOnScreen(int[])

2. 使用以下方法将gravity设置为toast

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

重要的是将烤面包的 x 坐标 设置为视图的右侧,例如 buttonView.getRight(),然后从 getLocationOnScreen() 中获取的 location[1] 得到 y 坐标

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);
            }

        }
    }

4
这个答案(https://dev59.com/rHvZa4cB1Zd3GeqP_B24#21026866)考虑到了 Toast 的大小,对我很有帮助。 - jayeffkay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接