[英]Android : holder.getSurface() always return null
我的觀點是一堆普通的小部件和一個表面視圖。 我不知道為什么在我得到surfaceholder
SurfaceView和使用getSurface()
再次對持有人,我會一直返回null。
這是我的示例代碼:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
}
@Override
public void onResume() {
super.onResume();
surface = (SurfaceView) findViewById(R.id.surfaceView);
this.holder = surface.getHolder();
if (holder.getSurface().isValid()){ // get surface again
Log.i("Notice","Surface holder is valid");
}
else
Log.i("Notice","Surface holder ISNOT valid"); //Always receive this
}
當我看到Android文檔的getSurface()
方法時。 這是怎么說的:
直接訪問表面對象。 Surface可能並不總是可用 - 例如,在使用SurfaceView時,在將視圖附加到窗口管理器並執行布局以確定Surface的尺寸和屏幕位置之前,不會創建支架的Surface。 因此,您通常需要實現Callback.surfaceCreated以找出Surface何時可用。
我不太了解這一點,但我知道我錯過了一些東西。 請解釋一下,並告訴我Callback.surfaceCreated
意思,以及如何實現它?
謝謝 :)
您正在嘗試使用表面尚不可用。 沒關系,它在Activity.onCreate
或Activity.onResume
方法中不可用,因為實際表面位於Activity窗口后面的單獨窗口中,並且具有自己的生命周期。 您需要實現SurfaceHolder.Callback以接收有關Surface
可用性的事件,並從單獨的線程進行繪制。 查看Android SDK示例文件夾中的LunarLander項目,它顯示了如何正確使用SurfaceView。
你的回調看起來像這樣:
public class MyCallback implements SurfaceHolder.Callback {
@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// you need to start your drawing thread here
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// and here you need to stop it
}
}
而且您需要將此回調設置為SurfaceHolder:
surface.getHolder().addCallback(new MyCallback());
我發現解決方案,這對我有用,感染錯誤是選擇正確的大小,所以使用MediaRecorder.setVideoSize()時使用此方法選擇最佳大小
private static Size chooseOptimalSize(Size[] choices, int width, int height) {
Size bigEnough = null;
int minAreaDiff = Integer.MAX_VALUE;
for (Size option : choices) {
int diff = (width*height)-(option.getWidth()*option.getHeight()) ;
if (diff >=0 && diff < minAreaDiff &&
option.getWidth() <= width &&
option.getHeight() <= height) {
minAreaDiff = diff;
bigEnough = option;
}
}
if (bigEnough != null) {
return bigEnough;
} else {
Arrays.sort(choices,new CompareSizeByArea());
return choices[0];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.