1

应用程序运行。它应该做的是在文本框中显示“=Heightofthescreen=”,其中Heightofthescreen是屏幕的实际值。然而,它只是给了我一个 0。我想这与我的上下文有关,但我不知道如何解决它。

活动类:

package com.example.measuringtesting;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class StartDraw extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Drawing.context2 = getApplicationContext();
        Drawing y = new Drawing(Drawing.context2);
        int theheight = y.width2;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_draw);
        TextView t = new TextView(this); 

        t=(TextView)findViewById(R.id.textView1); 
        t.setText("=" + theheight + "=");
    }
}

这是视图类:

package com.example.measuringtesting;

import android.content.Context;
import android.view.View;

public class Drawing extends View {
public Drawing(Context context) {
    super(context);
}

public float width;
public float height;
public int width2;
public int height2;
public static Context context2;

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
float parentWidth = MeasureSpec.getSize(widthMeasureSpec);
float parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.width = (float) (parentWidth*.15);
this.height = (float) (parentHeight*.15);
this.width2 = Math.round(width);
this.height2 = Math.round(height);
this.setMeasuredDimension(width2, height2);
}

}
4

1 回答 1

0

问题是onMeasure()在绘制布局之前不会调用它,这比您在 TextView 中设置文本的时间晚。所以现在y.width2还是0。

看看这个问题:我什么时候可以首先测量视图?

基本上,您必须在要测量的视图中添加GlobalLayoutListener一个ViewTreeObserver。您的视图的测量值将public void onGlobalLayout()GlobalLayoutListener.

于 2013-11-05T17:08:18.563 回答