我是一個初學者,使用圖形。現在我有一個圖像顯示在屏幕上隨機的地方。我想這樣做,如果圖像被觸摸,它應該被另一個圖像取代。我怎樣才能做到這一點? 我目前正在使用一個類中的一個class.Thanks在android中使用onTouch替換一個圖像
public class MainActivity extends ActionBarActivity implements OnTouchListener{
MyGameGraphics myGraphics;
TextView tvScore, tvPlayerScore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tvScore = (TextView)findViewById(R.id.showScore);
tvPlayerScore = (TextView)findViewById(R.id.playerScore);
myGraphics = new GraphicsMain(this);
myGraphics.setOnTouchListener(this);
setContentView(myGraphics);
}
@Override
protected void onPause(){
super.onPause();
myGraphics.pause();
}
@Override
protected void onResume(){
super.onResume();
myGraphics.resume();
}
@Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
// How to change image using touch event here?
return false;
}
public class MyGameGraphics extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
Boolean isRunning = false;
int[] images = new int[]{R.drawable.image1, R.drawable.image2};
public MyGameGraphics(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause(){
isRunning = false;
while(true){
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume(){
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
@Override
public void run() {
while(isRunning){
if(!ourHolder.getSurface().isValid())
continue;
Canvas ourCanvas = ourHolder.lockCanvas();
ourCanvas.drawRGB(0, 0, 0);
Random rn = new Random();
int location = rn.nextInt(12);
for(int i = 0; i < 500; i++){
try {
Random rn2 = new Random();
int generateWidthLocation = rn2.nextInt(420);
int generateHeightLocation = rn2.nextInt(600);
Bitmap btmp = BitmapFactory.decodeResource(getResources(), images[location]);
ourCanvas.drawBitmap(btmp, generateWidthLocation, generateHeightLocation, null);
ourThread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourHolder.unlockCanvasAndPost(ourCanvas);
}
}
}
另一件事}
可否請您用代碼解釋,我無法實現它。謝謝 – artist
我已經添加了代碼。 –