在我的Android应用程序中,当我旋转/倾斜我的设备时,我想在相反方向旋转我的按钮控件,这会补偿设备的方向。有点像android中的屏幕方向的想法
这是我的传感器类:
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
synchronized (this) {
double alpha = 0.8;
double gravity[] = new double[3];
switch (event.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
// alpha is calculated as t / (t + dT)
// with t, the low-pass filter's time-constant
// and dT, the event delivery rate
//gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
//gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
//gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
//sensorX = event.values[0] - gravity[0];
//sensorY = event.values[1] - gravity[1];
//sensorZ = event.values[2] - gravity[2];
//ignore this section!
break;
case Sensor.TYPE_ORIENTATION:
sensorZ = event.values[0];
sensorX = event.values[1];
sensorY = event.values[2];
outputZ.setText("Z:"+Float.toString(event.values[0]));
outputX.setText("X:"+Float.toString(event.values[1]));
outputY.setText("Y:"+Float.toString(event.values[2]));
//Toast.makeText(getApplicationContext(), "SWITCH TO ",Toast.LENGTH_LONG).show();
//RelativeLayout s_r_t = (RelativeLayout) findViewById(R.id.snap_r_t);
//RotateView r_flash = new RotateView(this , s_r_t.getWidth(), s_r_t.getHeight(), 90)(RotateView) findViewById(R.id.flash);
//RotateView r_flash = new RotateView(this , s_r_t.getWidth(), s_r_t.getHeight(), 90);
s_r_t.addView(r_flash);
//s_r_t.setLayoutParams(params)
//flash.getWidth();
//flash.getHeight();
break;
}
}
}
以及我的扩展按钮:
public class RotateView extends Button {
private float cx,cy;
private double degree;
private Button button;
public RotateView(Context context , int x, int y, double deg) {
super(context);
cx = (float)x/2;
cy = (float)y/2;
degree = deg;
}
public RotateView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate((float)degree,cx,cy);
super.onDraw(canvas);
canvas.restore();
}
}
如何使用扩展按钮类创建我的按钮?
这是我的按钮:
flash = (Button)findViewById(R.id.flash);
基本上,这就是我想要实现的(伪代码):
new button = find my button id;
onSensorChanged{
set button rotation to sensor.getdata degrees;
}
如果可能的话,请提供代码的完整部分,我看到很多答案几乎回答了我的问题,但是错过了如何在我的主要班级中将扩展按钮实现回我的按钮的基本部分。
答案 0 :(得分:1)
ImageButton button= (ImageButton) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.test);
Matrix mat = new Matrix();
mat.postRotate(deg);
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(), bMap.getHeight(), mat, true);
button.setImageBitmap(bMapRotate);
答案 1 :(得分:0)
供将来参考,请遵循android dev关于自定义组件的指南;
在我的情况下,我忘了添加xml布局
程序就像这样 - >
为组件创建一个类,然后覆盖我想要更改的部分
在这种情况下:
void setValue(double deg) {//this changes the rotation of canvas....
degree = deg;
}
为自定义类添加xml
在我的活动中查找视图并进行更改
完成
答案 2 :(得分:-1)
你可以使用 。button.animate()旋转(度);