在位置x,y上设置TextView

时间:2015-12-02 20:49:59

标签: android textview position touch screen

您好我想在用户触摸按钮时在TextView上显示一个String。但我希望这个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 个答案:

答案 0 :(得分:1)

将textView global声明为该活动

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