XML中的Android自定义视图不会绘制

时间:2016-03-30 19:22:04

标签: android xml android-layout user-interface android-custom-view

我编写了一个名为GameView的自定义视图,它运行正常,很好地绘制了所有内容,但当我在XML中包含此自定义视图时,应用程序已运行,但自定义视图中没有任何内容被绘制出来。

以下代码:

GameView 类是 NewGame 的内部类

public class NewGame extends Activity {
GameView game_view;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    game_view = new GameView(this);

    setContentView(R.layout.activity_new_game);
}

public static class GameView extends SurfaceView implements Runnable {
    Thread game_thread = null;

    // SurfaceHolder for Paint and Canvas in a thread
    SurfaceHolder the_holder;

    // Canvas and Paint objects
    Canvas canvas;
    Paint paint;
    Bitmap dragon;

    long fps; // tracks the game frame rate
    private long time_this_frame; // calculate the fps
    float x_position = 0;  // start position
    float y_position = 0;
    long frame_ticker = 0l;

    // New variables for spritesheet

    private int frame_count = 10;  
    private int sprite_width = 600;
    private int sprite_height = 450;
    private int current_frame = 0; // Start at the first frame - where else?

    // A rectangle to define an area of the sprite sheet that represents 1 frame
    private Rect frame_to_draw = new Rect(0, 0, sprite_width, sprite_height);

    // A rect that defines an area of the screen on which to draw
    RectF where_to_draw = new RectF(x_position, 0, x_position + sprite_width, sprite_height);

    // When the we initialize (call new()) on gameView
    // This special constructor method runs
    public GameView(Context context) {
        super(context);
        init(context);
    }

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public GameView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);

    }

    private void init(Context context) {
        // Initialize ourHolder and paint objects
        the_holder = getHolder();
        paint = new Paint();

        // Load dragon from .png file
        dragon = BitmapFactory.decodeResource(this.getResources(), R.drawable.gd10_spritesheet);
    }

    @Override
    public void run() {
        while (true) {
            // Capture the current time in milliseconds in startFrameTime
            long startFrameTime = System.currentTimeMillis();

            // Update the frame
            update();

            // Draw the frame
            draw();

            // Calculate the fps this frame
            // We can then use the result to
            // time animations and more.
            time_this_frame = System.currentTimeMillis() - startFrameTime;
            if (time_this_frame >= 1) {
                fps = 5000 / time_this_frame;
            }
        }
    }

    // Everything that needs to be updated goes in here
    // In later projects we will have dozens (arrays) of objects.
    // We will also do other things like collision detection.
    public void update() {
        long game_time = System.currentTimeMillis();

        if (game_time > (frame_ticker + fps)) {
            frame_ticker = game_time;

            current_frame++;
            if (current_frame >= frame_count) {
                current_frame = 0;
            }
        }

        frame_to_draw.left = current_frame * sprite_width;
        frame_to_draw.right = frame_to_draw.left + sprite_width;
    }

    // Draw the newly updated scene
    public void draw() {
        // Make sure our drawing surface is valid or we crash
        if (the_holder.getSurface().isValid()) {
            // Lock the canvas ready to draw
            canvas = the_holder.lockCanvas();
            //Log.d("test", "in if of draw()");
            // Draw the background color
            canvas.drawColor(Color.argb(255, 144, 195, 212));

            // Choose the brush color for drawing
            paint.setColor(Color.argb(255, 249, 129, 0));

            x_position = (float) (this.getWidth()/2.0 - frame_to_draw.width()/2.0);
            y_position = (float) (this.getHeight()/4.0 - frame_to_draw.height()/2.0);

            where_to_draw.set((int) x_position,
                    (int) y_position,
                    (int) x_position + sprite_width,
                    (int) y_position + sprite_height);

            canvas.drawBitmap(dragon,
                    frame_to_draw,
                    where_to_draw, paint);

            // Draw everything to the screen
            the_holder.unlockCanvasAndPost(canvas);
        }
    }

    public void getCurrentFrame(){

        long time  = System.currentTimeMillis();

        /*current_frame++;
        if (current_frame >= frame_count)
            current_frame = 0;*/

        //update the left and right values of the source of
        //the next frame on the spritesheet
        frame_to_draw.left = current_frame * sprite_width;
        frame_to_draw.right = frame_to_draw.left + sprite_width;

    }

    public void pause() {
        try {
            game_thread.join();
        } catch (InterruptedException e) {
            Log.e("Error:", "joining thread");
        }

    }

    public void resume() {
        game_thread = new Thread(this);
        game_thread.start();
    }
}

// This method executes when the player starts the game
@Override
protected void onResume() {
    super.onResume();

    // Tell the gameView resume method to execute
    game_view.resume();
}

// This method executes when the player quits the game
@Override
protected void onPause() {
    super.onPause();

    // Tell the gameView pause method to execute
    game_view.pause();
  }
}

activity_new_game.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.xuan.tictactoe.NewGame">

<view class="com.example.xuan.tictactoe.NewGame$GameView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</RelativeLayout>

因此,当我执行此操作时它不起作用,但如果onCreate NewGame setContentView(game_view) if (the_holder.getSurface().isValid()),那么程序会运行并执行我想要的操作。我做了一些调试,发现当我在XML文件中包含自定义视图时,onDrawGameView <script type="text/javascript"> var visitors = document.getElementById('tb254597').value; function limitVisitors() { if ( visitors > 60 ) { alert("We can only accommodate 60 people on a group visit. You entered " + visitors + " visitors."); } } </script> 下的Config.groovy返回false,所以事情不会得到。

不知道为什么它会返回false。我只想将自定义视图与XML中的一些小部件一起使用。有什么建议吗?谢谢!

0 个答案:

没有答案