2013-01-22 33 views
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; 
} 
} 

所以,现在的问题是,我想显示旁边的复选框敬酒,我试着用setGravity()工作,但它只是没有处理,并已经打了很长时间,但没有任何进展

如何显示在复选框旁边的烤面包。

回答

10

好了,我终于想通了如何获取复选框或另一种观点认为

您需要的视图的屏幕获得位置旁烤面包,由

buttonView.getLocationOnScreen(location); 

更多的参考,看到使用

2.设置重力来敬酒0

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

这里最重要的设置敬酒的x-coordinate到的观点正确, 例如,buttonView.getRight()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); 
      } 

     } 
    } 
+4

这个答案HTTP GET得到y坐标://计算器.com/a/21026866/630833,考虑到Toast的大小,这对我很有帮助。 – jayeffkay