为什么选择setContentView(Layout);在android中的新线程中不起作用

时间:2012-04-04 14:50:05

标签: android textview

我正在制作一款我几乎完成的Android游戏。我需要添加一个TextView,显示用户剩下的生命。但似乎我不能在这个帖子中使用setContentView方法。

我该如何使这项工作?我试了一下但是没用。请查看我的setUpGameDesign()方法。

代码:

package com.mysoftwaremobileapps.ParachuteHunter;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ExampleView extends SurfaceView implements SurfaceHolder.Callback
{
class ExampleThread extends Thread
{
    private ArrayList<Parachuter> parachuters;
    private Bitmap parachuter;
    private Paint black;

    private boolean running;

    private SurfaceHolder mSurfaceHolder;
    private Context mContext;
    private Context mContext1;
    private Handler mHandler;
    private Handler mHandler1;
    private GameScreenActivity mActivity;

    private long frameRate;
    private boolean loading;
    public float x;
    public float y;
    public float x1;
    public float y1;
    public MediaPlayer mp1;
    public int parachuterIndexToResetAndDelete;
    public int canvasGetWidth;
    public int canvasGetHeight;
    public int livesLeftValue;
    TextView livesLeftValueText;

    public ExampleThread(SurfaceHolder sHolder, Context context, Handler handler)
    {
        mSurfaceHolder = sHolder;
        mHandler = handler;
        mHandler1 = handler;
        mContext = context;
        mActivity = (GameScreenActivity) context;

        parachuters = new ArrayList<Parachuter>();
        parachuter = BitmapFactory.decodeResource(getResources(), R.drawable.parachuteman);
        black = new Paint();
        black.setStyle(Paint.Style.FILL);
        black.setColor(Color.GRAY);

        running = true;

        // This equates to 26 frames per second.
        frameRate = (long) (1000 / 26);
        loading = true;
    }

    @Override
    public void run()
    {
        while (running)
        {
            Canvas c = null;
            try
            {
                c = mSurfaceHolder.lockCanvas();

                synchronized (mSurfaceHolder)
                {
                    long start = System.currentTimeMillis();
                    doDraw(c);
                    long diff = System.currentTimeMillis() - start;

                    if (diff < frameRate)
                        Thread.sleep(frameRate - diff);
                }
            } catch (InterruptedException e)
            {
            }
            finally
            {
                if (c != null)
                {
                    mSurfaceHolder.unlockCanvasAndPost(c);
                }
            }
        }
    }

    protected void doDraw(Canvas canvas)
    {
        canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), black);
        canvasGetWidth = canvas.getWidth();
        canvasGetHeight = canvas.getHeight();

        //Draw
        for (int i = 0; i < parachuters.size(); i++)
        {
            canvas.drawBitmap(parachuter, parachuters.get(i).getX(), parachuters.get(i).getY(), null);
            parachuters.get(i).tick();
        }

        //Remove
        for (int i = 0; i < parachuters.size(); i++)
        {
        if (parachuters.get(i).getY() > canvas.getHeight()) {
            parachuters.remove(i);
            onPlaySound();
            checkLivesLeftValue();
        } else if(parachuters.get(i).isTouched()) {
            parachuters.remove(i);
        }
        }
    }


    private void checkLivesLeftValue() {
        Log.d("checkLivesLeftValue", "lives = " + livesLeftValue);
        // TODO Auto-generated method stub
        if (livesLeftValue == 3) {
            //Message to display: "You lost!
            livesLeftValueText.setText("Lives left=0");
            Log.d("checkLivesLeftValue", "calling onMethod now");
            onMethod();
        }
        else if (livesLeftValue == 2) {
            livesLeftValueText.setText("Lives left=1");
            livesLeftValue = livesLeftValue + 1;
            Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue);
        }
        else if (livesLeftValue == 1) {
            livesLeftValueText.setText("Lives left=2");
            livesLeftValue = livesLeftValue + 1;
            Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue);
        }
        else {
            //Set livesLeftValueText 3
            livesLeftValueText.setText("Lives left=3");
            livesLeftValue = livesLeftValue + 1;
            Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue);
        }
    }
    public void onMethod() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "You lost!", 15).show();
                livesLeftValue = 0;
                //Tell the user that he lost:
                android.content.Context ctx = mContext;
                Intent i = new Intent(ctx, playerLostMessageActivity.class);  
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ctx.startActivity(i);
                System.exit(0);
            }
        });
    }

    public void onPlaySound()
    {
        try {
        mp1 = MediaPlayer.create(getContext(), R.raw.bombsound);
        mp1.start();
        } catch (Exception e) {
            e.printStackTrace();
            mp1.release();
        }
    }

    public void onPlaySound1()
    {
        try {
        mp1 = MediaPlayer.create(getContext(), R.raw.airriflesoundeffect);
        mp1.start();
        } catch (Exception e) {
            e.printStackTrace();
            mp1.release();
        }
    }

    public boolean onTouchEvent(MotionEvent event)
    {
        if (event.getAction() != MotionEvent.ACTION_DOWN)
        Toast.makeText(getContext(), "onTouchEvent invoked. X= " + event.getX() + " Y= " + event.getY(), 15).show();
        x1 = event.getX();
        y1 = event.getY();
        removeParachuter();
        return false;
    }

    public void removeParachuter()
    {
        try {
        for (Parachuter p: parachuters) {
            if (x1 > p.getX() && x1 < p.getX() + parachuter.getWidth() && y1 > p.getY() && y1 < p.getY() + parachuter.getHeight()) {
                p.setTouched(true);
                Toast.makeText(getContext(), "Setting touched(true) to the parachuter", 25).show();
                onPlaySound1();
                p.setTouched(false);
            }
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setUpGameDesign()
    {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                setContentView(livesLeftValueText);
            }
        });
    }

    public void initiateDrawParachuters()
    {
        drawParachutersGroup1();
    }
    public void drawParachutersGroup1() {
        // TODO Auto-generated method stub
        //Parachuter group nr. 1

        //Parachuter nr. 2
        x = 75;
        y = 77;

        Parachuter p1 = new Parachuter(x, y);
        parachuters.add(p1);
        //Parachuter nr.1
        x = 14;
        y = 28;

        Parachuter p = new Parachuter(x, y);
        parachuters.add(p);

        //Parachuter nr. 3
        x = 87;
        y = 94;

        Parachuter p3 = new Parachuter(x, y);
        parachuters.add(p3);

        //Parachuter nr. 3
        x = 85;
        y = 80;

        Parachuter p2 = new Parachuter(x, y);
        parachuters.add(p2);

        //Parachuter nr. 5
        x = 67;
        y = 163;

        Parachuter p5 = new Parachuter(x, y);
        parachuters.add(p5);

        x = 217;
        y = 118;

        Parachuter p4 = new Parachuter(x, y);
        parachuters.add(p4);

        //Parachuter nr. 7
        x = 297;
        y = 247;

        Parachuter p7 = new Parachuter(x, y);
        parachuters.add(p7);

        //Parachuter nr. 6
        x = 19;
        y = 57;

        Parachuter p6 = new Parachuter(x, y);
        parachuters.add(p6);
    }

    public void drawParachutersGroup2() {
        // TODO Auto-generated method stub
        //Parachuter group nr. 2

        //Parachuter nr. 5
        x = 57;
        y = 166;

        Parachuter p5 = new Parachuter(x, y);
        parachuters.add(p5);

        x = 283;
        y = 123;

        Parachuter p4 = new Parachuter(x, y);
        parachuters.add(p4);

        //Parachuter nr. 7
        x = 99;
        y = 213;

        Parachuter p7 = new Parachuter(x, y);
        parachuters.add(p7);

        //Parachuter nr. 6
        x = 231;
        y = 121;

        Parachuter p6 = new Parachuter(x, y);
        parachuters.add(p6);
    }

    public void drawParachutersGroup3() {
        // TODO Auto-generated method stub
        //Parachuter group nr. 3

        //Parachuter nr. 2
        x = 33;
        y = 115;

        Parachuter p1 = new Parachuter(x, y);
        parachuters.add(p1);
        //Parachuter nr.1
        x = 277;
        y = 183;

        Parachuter p = new Parachuter(x, y);
        parachuters.add(p);

        //Parachuter nr. 3
        x = 127;
        y = 280;

        Parachuter p3 = new Parachuter(x, y);
        parachuters.add(p3);

        //Parachuter nr. 3
        x = 84;
        y = 80;

        Parachuter p2 = new Parachuter(x, y);
        parachuters.add(p2);

        //Parachuter nr. 5
        x = 67;
        y = 112;

        Parachuter p5 = new Parachuter(x, y);
        parachuters.add(p5);

        x = 260;
        y = 89;

        Parachuter p4 = new Parachuter(x, y);
        parachuters.add(p4);

        //Parachuter nr. 7
        x = 283;
        y = 113;

        Parachuter p7 = new Parachuter(x, y);
        parachuters.add(p7);

        //Parachuter nr. 6
        x = 295;
        y = 25;

        Parachuter p6 = new Parachuter(x, y);
        parachuters.add(p6);
    }

    public void drawParachutersGroup4() {
        // TODO Auto-generated method stub
        //Parachuter group nr. 1

        //Parachuter nr. 2
        x = 75;
        y = 166;

        Parachuter p1 = new Parachuter(x, y);
        parachuters.add(p1);
        //Parachuter nr.1
        x = 118;
        y = 94;

        Parachuter p = new Parachuter(x, y);
        parachuters.add(p);

        //Parachuter nr. 3
        x = 38;
        y = 55;

        Parachuter p3 = new Parachuter(x, y);
        parachuters.add(p3);

        //Parachuter nr. 3
        x = 22;
        y = 18;

        Parachuter p2 = new Parachuter(x, y);
        parachuters.add(p2);

        //Parachuter nr. 5
        x = 67;
        y = 119;

        Parachuter p5 = new Parachuter(x, y);
        parachuters.add(p5);

        x = 217;
        y = 113;

        Parachuter p4 = new Parachuter(x, y);
        parachuters.add(p4);

        //Parachuter nr. 7
        x = 345;
        y = 234;

        Parachuter p7 = new Parachuter(x, y);
        parachuters.add(p7);

        //Parachuter nr. 6
        x = 346;
        y = 44;

        Parachuter p6 = new Parachuter(x, y);
        parachuters.add(p6);
    }

    public void drawParachuters()
    {
            Parachuter p = new Parachuter(x, y);
            parachuters.add(p);
            Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();
    }

    public void setRunning(boolean bRun)
    {
        running = bRun;
    }

    public boolean getRunning()
    {
        return running;
    }
}

/** Handle to the application context, used to e.g. fetch Drawables. */
private Context mContext;

/** Pointer to the text view to display "Paused.." etc. */
private TextView mStatusText;

/** The thread that actually draws the animation */
private ExampleThread eThread;

public ExampleView(Context context)
{
    super(context);

    // register our interest in hearing about changes to our surface
    SurfaceHolder holder = getHolder();
    holder.addCallback(this);

    // create thread only; it's started in surfaceCreated()
    eThread = new ExampleThread(holder, context, new Handler()
    {
        @Override
        public void handleMessage(Message m)
        {
           // mStatusText.setVisibility(m.getData().getInt("viz"));
           // mStatusText.setText(m.getData().getString("text"));
        }
    });

    setFocusable(true);
}

@Override
public boolean onTouchEvent(MotionEvent event)
{
    return eThread.onTouchEvent(event);
}

public ExampleThread getThread()
{
    return eThread;
}

@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
    // TODO Auto-generated method stub
}

public void surfaceCreated(SurfaceHolder holder)
{
    if (eThread.getState() == Thread.State.TERMINATED)
    {
        eThread = new ExampleThread(getHolder(), getContext(), getHandler());
        eThread.start();
    }
    else
    {
        eThread.start();
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
    boolean retry = true;
    eThread.setRunning(false);

    while (retry)
    {
        try
        {
            eThread.join();
            retry = false;
        }
        catch (InterruptedException e)
        {
        }
    }
}
}

错误:

The method setContentView(TextView) is undefined for the type new Runnable(){}

2 个答案:

答案 0 :(得分:0)

方法setContentViewActivity中声明,尽管它在UI线程上运行但它仍然引用Activity。 您无法将View(您的ExampleView)替换为其他人。

尝试在托管Activity的{​​{1}}中更改布局。

答案 1 :(得分:0)

Android包含一个便利功能,用于在另一个线程的UI线程上运行东西。基本上你必须创建一个'runnable',这只是一个函数,并在活动线程上执行它。你可以这样做:

activity.runOnUiThread(new Runnable() {
    public void run() {
        safeSendJavascript(String.format(jsStr, registrationId,registrationId));
    }
});