通过addView()显示两个View对象

时间:2015-07-03 13:14:42

标签: java android

我编写了以下代码。但是它只能显示 textView 对象而无法显示绘图对象。问题是什么?

MainActivity.java

public class MainActivity extends Activity {
    Draw draw;
    Cal cal;
    TextView textView;
    RelativeLayout linearLayout;
Canvas canvas;
 Paint paint;
    public void onCreate(Bundle s) {
        super.onCreate(s);
        setContentView(R.layout.activity_main);

        linearLayout = (RelativeLayout) findViewById(R.id.t);
        cal = new Cal(this);
        cal.cal();

        textView = new TextView(getApplicationContext());
        textView.setText("" + cal.result);
        textView.setTextColor(Color.RED);

        draw = new Draw(this);
canvas = new Canvas();
        paint = new Paint();
        draw.d(canvas, paint);
        linearLayout.addView(draw);
        linearLayout.addView(textView);
    }}

Draw.java

public class Draw extends View {

public Draw(Context context) {
    super(context);
}
public void d(Canvas canvas, Paint paint) {

    paint.setColor(Color.BLUE);
    canvas.drawCircle(120,120,40,paint);
    }
}

Cal.java

public class Cal extends View {
   public Cal(Context context){
        super(context);
    }
    public double result;
    double parameter = (Math.pow(40,2)) * 3.14;
    public void cal(){
        result = Math.sqrt(parameter);

    }
}

有什么问题?.......................................... .................................................. .................................................. .....

5 个答案:

答案 0 :(得分:1)

您应该在系统提供的Canvas上绘制View.onDraw(),而不是创建自己的Canvas。

http://developer.android.com/training/custom-views/custom-drawing.html

此外,您应该为" Draw"设置适当的尺寸。视图。默认情况下,它的大小为零。

答案 1 :(得分:0)

检查您的activity_main布局文件。将linearlayout的宽度和高度设置为match_parent。并且还将方向设置为垂直方向。

答案 2 :(得分:0)

将布局R.id.t从RelativeLayout更改为LinearLayout

答案 3 :(得分:0)

您需要使用索引添加视图,

linearLayout.addView(draw,0);
        linearLayout.addView(textView,1);

答案 4 :(得分:0)

您必须设置自定义视图的高度和宽度。而且您绘制自定义视图的方式也不正确。

我已经更新了你的课程,你可以运行并测试它们。

public class MainActivity extends Activity {

Draw draw;
Cal cal;
TextView textView;
RelativeLayout linearLayout;
Canvas canvas;
Paint paint;

public void onCreate(Bundle s) {
    super.onCreate(s);
    setContentView(R.layout.activity_main);

    linearLayout = (RelativeLayout) findViewById(R.id.t);
    cal = new Cal(this);
    cal.cal();

    textView = new TextView(getApplicationContext());
    textView.setText("" + cal.result);
    textView.setTextColor(Color.RED);

    draw = new Draw(this);

    LayoutParams layoutParams = new LayoutParams(200, 200);
    draw.setLayoutParams(layoutParams);

    linearLayout.addView(draw);
    linearLayout.addView(textView);
}}

public class Draw extends View {
Paint paint;

public Draw(Context context) {
    super(context);
    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}

@Override
protected void onDraw(Canvas canvas) {
    paint.setColor(Color.BLUE);
    canvas.drawCircle(120, 120, 40, paint);
    super.onDraw(canvas);
}}