如何以编程方式在CustomView上放置TextView?

时间:2015-04-27 01:00:15

标签: android

在我的应用程序中,我设计了一个自定义视图,这里是代码

public class Tunnel extends View implements View.OnTouchListener {

    Paint paint = new Paint();

    public Tunnel(Context context) {
        super(context);
        setOnTouchListener(this);
    }

    @Override
    public void onDraw(Canvas canvas) {
        paint.setColor(Color.RED);
        for (int x = 0; x < canvas.getWidth(); x++) {
            canvas.drawLine(x, (float) upperBound(x), x, (float) lowerBound(x), paint);
        }
        setBackgroundColor(Color.BLACK);
    }

    private double upperBound(double x) {
        return 50 * Math.sin(x / 50) + 400;
    }

    private double lowerBound(double x) {
        return 50 * Math.sin(x / 50) + 600;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }
}

它看起来像这样

enter image description here

现在我需要做的是在此视图上添加一个自定义TextView,它将显示一些文本。据我所知,我的构造函数应该看起来像这样

    public Tunnel(Context context) {
        super(context);
        setOnTouchListener(this);
        TextView tv = new TextView(getContext());
        tv.setX(200);
        tv.setY(200);
        //todo show the textView
    }

但我不知道下一步该写些什么。如何将textView应用于我的视图? 提前致谢

2 个答案:

答案 0 :(得分:0)

尝试

 public Tunnel(Context context) {
        super(context);
        setOnTouchListener(this);
        TextView tv = new TextView(getContext());
        tv.setX(200);
        tv.setY(200);
        tv.setText("Text");
        TheCustomView.addView(tv);
    }

答案 1 :(得分:0)

我从线性布局继承了我的自定义视图,将其设置为执行onDraw方法,并且它对我有用

START TRANSACTION;
-- INSERT BLOCK FOR login_info
-- GET THE NEEDED KEY FROM login_info LAST INSERT
-- INSERT BLOCK FOR employee
-- INSERT BLOCK FOR address
COMMIT;
相关问题