我创建了自定义thread
,并使用postInvalidate
方法调用并移动图片,但我的Null Pointer Exception
有Thread class AnimThread for PostInvalidate
。
package com.example.ahmad.ballmoving;
import android.view.View;
/**
* Created by Ahmad on 7/30/2015.
*/
public class AnimThread extends Thread {
private View threadView;
public AnimThread(View view )
{
if(view!=null) {
threadView = view;
}
}
@Override
public void run()
{
while(true) {
try {
Thread.sleep(1000);
threadView.postInvalidate();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
这是我的自定义视图类。
package com.example.ahmad.ballmoving;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by Ahmad on 7/29/2015.
*/
public class MyContextView extends View
{
int xVelocity=1;
int yVelocity=1;
private Runnable runn;
Bitmap imag1;
int x=0,y=0;
public MyContextView(Context context, AttributeSet att)
{
super(context);
imag1=BitmapFactory.decodeResource(getResources(),R.drawable.images);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
x=x+xVelocity;
y=y+yVelocity;
//canvas.save();
//invalidate();
canvas.drawBitmap(imag1, x, y, null);
}
}
这是我的主要课程
package com.example.ahmad.ballmoving;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
private Thread thread1;
private Thread thread2;
public MyContextView mcv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyContextView c = (MyContextView)findViewById(R.id.ko);
Thread a = new AnimThread(c);
a.start();
}
}
这是我的主类XML:
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<com.example.ahmad.ballmoving.MyContextView
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id="@+id/ko"/>
</RelativeLayout>
答案 0 :(得分:0)
您可以尝试 CountDownTimer 吗?
new CountDownTimer(1000,100) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
threadView.postInvalidate();
}
}.start();
希望这会对你有所帮助。