最近在开发Launcher,界面上有一个功能是播放电视节目,也就是一个小的播放窗口。使用SurfaceView来实现的。具体的实现过程就不细说了。在设置显示界面的时候,一开始时自己根据调试写了显示的坐标宽高,这样会导致总是存在偏差,不是显示的大了就是小了,或是位置不对劲。
VideoWindowType videoWindowType = new VideoWindowType();
videoWindowType.x = 106;
videoWindowType.y = 210;
videoWindowType.width = 660;
videoWindowType.height = 340;后来改了一种实现,直接获取布局文件中用于显示控件的位置以及控件的宽高:
PanelProperty tempPanelSize;
tempPanelSize = TvManager.getInstance().getPictureManager()
.getPanelWidthHeight();
int osdWidth = getApplicationContext().getResources()
.getDisplayMetrics().widthPixels;
int osdHeight = getApplicationContext().getResources()
.getDisplayMetrics().heightPixels;
float zoomratio = ((float) tempPanelSize.width / (float) osdWidth);
VideoWindowType videoWindowType = new VideoWindowType();
int[] location = new int[2];
tv_surfaceview_layout.getLocationOnScreen(location);
videoWindowType.x = (int) (location[0] * zoomratio);
videoWindowType.y = (int) (location[1] * zoomratio);
videoWindowType.width = (int) (tv_surfaceview_layout.getWidth() * zoomratio) - 2;
videoWindowType.height = (int) (tv_surfaceview_layout.getHeight() * zoomratio) - 2;本来以为会万事大吉正常显示,哪知道在界面上根本就没有显示出来,查看打印消息才知道location[0],
location[1],getWidth、getHeight等都为0。一下就懵了。。。。。。
经过分析才知道在UI组件还没有显示在界面之前调用getWidth、getHeight、getX、getY等通常都是为0。不要在onCreate、onStart、onResume中去得到控件的getWidth、getHeight、getX、getY等信息。
然后在网上找到了大神们的解决方式:
在onResume中添加:
getWindow().getDecorView().post(new Runnable() {
@Override
public void run() {
scaleHandler.post(scaleRunnable);
}
});其中scaleHandler和
scaleRunnable的定义为:
private Handler scaleHandler = new Handler();
private Runnable scaleRunnable = new Runnable() {
@Override
public void run() {
setPipscale(); //具体的处理函数,里面有获取X,Y,宽高等信息,之前是直接在onResume中被调用。
}
};修改以后,就可以成功获取X,Y,宽高等信息。
同时,也可以用这种方法来进行延迟加载。
具体的解析看博客:
http://www.androidperformance.com/2015/11/18/Android-app-lunch-optimize-delay-load.html
http://www.androidperformance.com/2015/12/29/Android%E5%BA%94%E7%94%A8%E5%90%AF%E5%8A%A8%E4%BC%98%E5%8C%96-%E4%B8%80%E7%A7%8DDelayLoad%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%92%8C%E5%8E%9F%E7%90%86-%E4%B8%8B%E7%AF%87.html
无限崇拜大神中~