2015-12-02 102 views
0

你好我想在用户触摸一个按钮时在TextView上显示一个字符串。但是我希望这个TextView能够显示在用户触摸屏幕的相同位置。目前,我有以下的代码,但它不工作了:在位置x,y上设置TextView

private void set(Integer name, Float x, Float y, Typeface font) { 

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
      RelativeLayout.LayoutParams.MATCH_PARENT, 
      RelativeLayout.LayoutParams.MATCH_PARENT); 
    layoutParams.setMargins(10, 1, 10, 1); 

    RelativeLayout nlap = new RelativeLayout(this); 
    nlap.setLayoutParams(layoutParams); 

    TextView tv1 = new TextView(this); 
    tv1.setX(x); 
    tv1.setY(y); 
    tv1.setText("+ " + String.valueOf(name)); 
    tv1.setTypeface(font); 
    tv1.setGravity(Gravity.CENTER); 
    tv1.setTextSize(20); 
    nlap.addView(tv1); 

} 

而在OnTouchListener:

int action = motionEvent.getAction(); 
      int x = (int)motionEvent.getX(); 
      int y = (int)motionEvent.getY(); 
      set(multiplicator, Float.intBitsToFloat(x), Float.intBitsToFloat(y), font); 

我希望你能帮助我。谢谢!

回答

1

申报的TextView全球该活动

TextView tv; 

然后在oncreate()方法

tv=(TextView) findViewById(R.id.your_xml_textview); 
tv.setText("your desired text"); 
tv.setVisibility(View.INVISIBLE); 

您也可以直接在你的XML使用android:visibility="invisible"现在

屏幕ontouch我们取得共同坐标并通过以下代码将textView放在该点上

@Override 
public boolean onTouchEvent(MotionEvent event) { 
int corx = (int)event.getX(); 
int cory = (int)event.getY(); 
tv.setX(corx); 
tv.setY(cory); 
tv.setVisibility(View.VISIBLE); 
switch (event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
    case MotionEvent.ACTION_MOVE: 
    case MotionEvent.ACTION_UP: 
} 
return false; 
} 
+0

好吧谢谢它的作品,但我想通了,我认为按钮的坐标不是在整个布局相同。你可以帮我吗? – mcjonesman