无法显示我的自定义SurfaceView的2个实例

时间:2012-05-08 21:32:51

标签: android tabs surfaceview

我已经创建了自己的自定义SurfaceView,它可以自行运行,但是当我尝试将两个放在TabWidget的单独选项卡上时,无论选择哪个选项卡,都只会显示一个,并且始终是应用程序启动时首次绘制的SurfaceView。

为了说明问题,我创建了可以编译显示问题的示例代码。

下面的SurfaceView,名为SurfaceViewCircle,只是创建一个位图,默认情况下绘制一个蓝色圆圈,然后显示它。有一个公共方法,changeColour(),它将改变位图中的圆形颜色。

其次,我创建了一个XML布局,它只包含一个SurfaceViewCircle实例。

在Activity类中,我创建一个TabWidget和主机等。然后我将上面的XML膨胀两次,但在一个实例中我将SurfaceViewCircle的颜色更改为红色。一旦应用程序运行,无论我选择哪个选项卡,当应用程序退出并显示蓝色圆圈时,红色圆圈始终显示为一个简短的实例。

有人能指出我在使用SurfaceView时错过了一步吗?

这是活动代码:

public class TestActivity extends Activity  {
/** Called when the activity is first created. */

private TabHost mTabHost;
private Context mTabHostContext;
private View surfaceView1, surfaceView2;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /*
     * Setup tabs
     */
    setContentView(R.layout.maintabs);
        setupTabHost(); //Prepares the TabHost from code rather than XML;
    mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider); //Sets a thin dividing line
    mTabHostContext = mTabHost.getContext();
    surfaceView1 = LayoutInflater.from(mTabHostContext).inflate(R.layout.surfaceviewindependent, null);
    SurfaceViewCircle s = (SurfaceViewCircle)surfaceView1.findViewById(R.id.circle1);
    /*
     * Change the colour to red
     */
    s.changeColour(getResources().getColor(R.color.red_square));

    /*
     * Create a second layout containing SurfaceViewCircle but leave circle as default blue.
     */
    surfaceView2 = LayoutInflater.from(mTabHostContext).inflate(R.layout.surfaceviewindependent, null);
    setupTab(surfaceView1,"SurfaceView1");
    setupTab(surfaceView2,"SurfaceView2");


}

private void setupTabHost() {
    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();
}

private void setupTab(final View view, final String tag) {
    View tabview = createTabView(mTabHost.getContext(), tag); // This creates a view to be used in the TAB only

    /* this creates the tab content AND applies the TAB created in the previous step in one go */
    TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
        public View createTabContent(String tag) {return view;}
    });
    mTabHost.addTab(setContent);

}

private static View createTabView(final Context context, final String text) {
    View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
    TextView tv = (TextView) view.findViewById(R.id.tabsText);
    tv.setText(text);

    return view;
}   
}

这是我的自定义SurfaceView:

public class SurfaceViewCircle extends SurfaceView implements SurfaceHolder.Callback{

private Paint paint, circlePaint;
private Bitmap bitmap = null;
private int w;
private int h;
private int colour = 0;
private Resources r = null;
private _Thread t = null;
private boolean surfaceIsCreated;

public SurfaceViewCircle(Context context) {
    super(context);
    initialise();
}

public SurfaceViewCircle(Context context, AttributeSet attrs) {
    super(context, attrs);
    initialise();
}

public SurfaceViewCircle(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    initialise();
}

private void initialise(){
    r = getResources();
    getHolder().addCallback(this);
    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setFilterBitmap(true);
    colour = R.color.blue_square;
    circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    circlePaint.setColor(r.getColor(colour));
    circlePaint.setStyle(Style.FILL);
    circlePaint.setStrokeWidth(0.02f);
    t = new _Thread(getHolder());


}

public void changeColour(int colour){
    circlePaint.setColor(colour);
    if (surfaceIsCreated){
        createBitmap();
    }
    synchronized (t){
        t.notify();
    }
}

private Bitmap createBitmap(){
    Bitmap b = null;
    b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    c.scale((float)w, (float)w);        //Scales the background for whatever pixel size
    c.drawCircle(0.5f, 0.5f, 0.5f, circlePaint);
    //c.drawColor(r.getColor(colour));
    return b;
}

public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    int width = measure(widthMeasureSpec);
    int height = measure(heightMeasureSpec);

    int d = Math.min(width, height);
    setMeasuredDimension(d,d);
}

private int measure(int measureSpec) {
    int result = 0;
    // Decode the measurement specifications
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    return specSize;
}

@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH){
    super.onSizeChanged(w, h, oldW, oldH);
    //synchronized (this){
        this.w = Math.min(w, h);
        this.h = w;
    //}
    Bitmap b = createBitmap();

        bitmap = b;

    Log.i("Square", "onSizeChanged() called.");


}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // TODO Auto-generated method stub

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    Log.i("Panel", "surfaceCreated() called.");
    t.setRunning(true);
    t.start();
    surfaceIsCreated = true;

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    Log.i("Square", "surfaceDestroyed() called.");

    surfaceIsCreated = false;
    boolean retry = true;
    synchronized (t){
        t.setRunning(false);
        t.notify();
    }
    while (retry) {
        try {
            t.join();
            retry = false;
        } catch (InterruptedException e) {
            // we will try it again and again...
        }
    }

}

private class _Thread extends Thread {
    private SurfaceHolder _surfaceHolder;
    private boolean _run = false;

    public _Thread(SurfaceHolder surfaceHolder) {
        _surfaceHolder = surfaceHolder;
    }

    public void setRunning(boolean run) {
        _run = run;
    }

    @Override
    public void run() {
        Canvas c = null;
        while (_run){
            try {
                c = _surfaceHolder.lockCanvas(null);
                synchronized (_surfaceHolder) {
                    synchronized(bitmap){
                        c.drawBitmap(bitmap, 0, 0, paint);
                    }
                }
            } finally {
                // do this in a finally so that if an exception is thrown
                // during the above, we don't leave the Surface in an
                // inconsistent state
                if (c != null) {
                    _surfaceHolder.unlockCanvasAndPost(c);
                }
            }
            synchronized(this){
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block

                }
            }
        }
    }
}
}

maintabs.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
        <TabWidget android:id="@android:id/tabs"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_marginLeft="0dip" android:layout_marginRight="0dip" />
            <FrameLayout android:id="@android:id/tabcontent"
            android:layout_width="fill_parent" android:layout_height="fill_parent" />
    </LinearLayout>
    </TabHost>
</LinearLayout>

和surfaceviewindependent.xml:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
<uk.co.androidcontrols.gauges.SurfaceViewCircle
android:id="@+id/circle1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="0.5"
    android:layout_margin="1dip">
</uk.co.androidcontrols.gauges.SurfaceViewCircle>
</LinearLayout>

我还注意到其他人遇到了类似的问题here.

对于格式不佳的道歉,但代码编辑器几乎无法用于大型代码报价!

其他信息

我尝试使用setVisibility()'中的onvisibilityChanged(),但最终会导致异常:

protected void onVisibilityChanged(View changedView, int visibility){
    super.onVisibilityChanged(changedView, visibility);
    changedView.setVisibility(visibility);
    Log.i("SurfaceViewCircle", "onVisibilityChanged() called.");
}

java.lang.IllegalThreadStateException: Thread already started.

每次调用changedView.setvisibility()都会破坏表面。

2 个答案:

答案 0 :(得分:4)

我根据您的代码构建了一个测试项目,并且令人惊讶地花费了将近几个小时的时间。我现在很快就会脱口而出,因为我应该掏腰包!

首先,您肯定会创建两个标签,每个标签都有一个单独的自定义SurfaceView实例。没关系。

现在,当Activity首次启动并显示第一个标签时,只会初始化第一个SurfaceView并调用surfaceCreated(),此时Thread会运行SurfaceView

当选择第二个标签页时,createTabContent()回调为其提供的第二个Activity将被初始化,就像第一个标签一样。从那时起,直到SurfaceView两个 surfaceDestroyed()的拆除仍然处于有效的表面状态。在标签之间切换永远不会在SurfaceView上调用SurfaceCreated(),因此永远不会再调用SurfaceView。首次创建后,也不会再次调用'onMeasure()'。因此,这告诉我两个View都保留在整个SurfaceViews层次结构中。 Thread'wait()都在运行,如果你没有SurfaceView,两者都会不断尝试渲染到视频内存。

如您所知,ViewSurfaceView层次结构中的位置(或者更确切地说,不是坐位)非常独特。这里似乎发生的事情是,要创建的第一个SurfaceView是在视频内存中看到输出的SurfaceView,无论选项卡选择如何。

我首先尝试的一件事是让第二个SurfaceView明显小于第一个SurfaceView,其中的圆圈比例较小。当从第一个标签(较大的SurfaceView大红色圆圈)切换到第二个标签(较小的SurfaceView较小的蓝色圆圈)时,我可以看到可见SurfaceView的大小减少了正确就好像第二个((SurfaceView)surfaceView1.findViewById(R.id.circle1)).setVisibility(View.GONE); ((SurfaceView)view.findViewById(R.id.circle1)).bringToFront(); 变得可见,但不是它的小蓝色圆圈可见,我只有很大一部分第一个bringToFront()的大红色圆圈穿过,但被裁剪了第二个setVisibility(View.GONE)的较小尺寸。

我最终玩的是以下两种方法调用:

SurfaceView

后者SurfaceView似乎没有取得任何成果。但是,就像第二个 TabHost选项卡一样,使用首先 every上的TabHost.OnTabChangeListener调用,然后很好地使用了它从红色圆圈切换到蓝色圆圈。

我认为你需要尝试做的是寻找一个合适的setVisibility() API回调方法来覆盖,选择一个标签时可以调用SurfaceView(可能使用{{1}})并将其用作{{1}}适当调用{{1}}的地方,以控制哪一个出现在最顶层。

答案 1 :(得分:1)

看起来我不建议使用SurfaceView做什么:link