程序中的 oncreate 方法
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
viewControl = controlInflater.inflate(R.layout.control, null);
image =(ImageView) viewControl.findViewById(R.id.img);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
}
control.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
/>
</LinearLayout>
如何通過點擊按鈕來刪除這個圖像。實際上我想從當前的像素位置把這個圖像轉移到別的位置。
我點擊按鈕來實現:
b =(Button)findViewById(R.id.button);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("Button clicked");
TranslateAnimation anim = new TranslateAnimation(0,0,200,200);
anim.setDuration(2000);
image.setAnimation(anim);
}
});
但是現在圖像會消失一倆秒鐘。哪裡出錯了呢是?事實上我想在 accelerometer 改變的時候移動圖像。
先寫一個xml文件放在drawable目錄下的anim目錄,沒有自己新建translate.xml
<?xml version="1.0" encoding="utf-8"?>
<translate
android:duration="2000"
android:fromXDelta="0"
android:repeatCount="1"
android:repeatMode="reverse"
android:toXDelta="200%p" />
//在代碼中
Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.translate);
// 開始執行動畫
image.startAnimation(animation);
如果想要去掉ImageView,需要先執行 image.clearAnimation();然後將image.setVisibility(View.GONE);
或者設置 image.setVisibility(View.INVISIBLE);