将Toast的dynamic位置设置为视图

首先这不是完整的代码

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

所以现在,问题是,我想显示在checkbox旁边的烤面包,我尝试使用setGravity() ,但它只是不workup,并已经打了很长时间,尝试,但没有进展

如何在checkbox旁边显示烤面包。

Solutions Collecting From Web of "将Toast的dynamic位置设置为视图"

好吧,我终于想出了如何在checkbox或其他视图旁边烤面包

你需要在视图的屏幕上获取位置,通过

 buttonView.getLocationOnScreen(location); 

有关更多参考,请参阅getLocationOnScreen(int [])

2.将重力设置为吐司使用

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

这里重要的是设置toast的x-coordinate到视图的右边,例如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); } } }