0
我是新來的android開發以及Java編程語言,並且肯定會很感謝這個問題的一些幫助。Android OnDraw和onTouchEvent不能一起工作
目前我有一些代碼創建一個畫布,並在其上繪製位圖圖片,這似乎工作。我還有一些代碼可以檢測用戶手指在設備屏幕上的位置,這也是可行的。當我嘗試將兩者結合時,位圖將顯示,但只要我點擊屏幕,應用程序就會崩潰。
我有一種感覺,這個問題是與此畫布/位圖一側,因爲我也注意到,任何窗口添加到佈局的小部件在畫布/位圖功能運行時消失。
這是帆布/位圖的代碼:
public class myView extends View{
Bitmap image;
DisplayMetrics metrics;
public myView(Context context) {
super(context);
metrics = context.getResources().getDisplayMetrics();
// TODO Auto-generated constructor stub
image = BitmapFactory.decodeResource(getResources(), R.drawable.bhead);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Matrix matrix = new Matrix();
float angle = 90;
float imageCenterX = 50;
float imageCenterY = 50;
matrix.setRotate(angle, imageCenterX, imageCenterY);
Bitmap temp;
temp = BitmapFactory.decodeResource(getResources(), R.drawable.bhead);
image = Bitmap.createScaledBitmap(temp, 100, 100,true);
matrix.postTranslate(((width/2)-50), ((height/2)-100));
canvas.drawBitmap(image, matrix, null);
}
}
,這是用於在屏幕上手指位置的代碼:
public class MainActivity extends ActionBarActivity {
myView mview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mview = new myView(this);
setContentView(mview);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
}
EditText txt = (EditText)findViewById(R.id.editText1);
txt.setText("X = "+ x +" Y = " + y);
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
從logcat發佈完整的堆棧跟蹤。 – Karakuri 2014-10-05 14:40:59