应用程序运行。它应该做的是在文本框中显示“= 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);
}
}
答案 0 :(得分:0)
问题是在绘制布局之前不会调用onMeasure()
,这比在TextView中设置文本的时间晚一些。所以现在y.width2
仍然是0.
看看这个问题:When Can I First Measure a View?
基本上,您必须将GlobalLayoutListener
添加到要测量的视图的ViewTreeObserver
。您可以在public void onGlobalLayout()
的{{1}}回调中找到您的观看次数。