我推荐了一些网站,但我不明白如何从旋钮中获得价值。下面给出了我尝试的示例代码。我需要的是在右侧旋转旋钮时要在文本视图中增加值,而在左侧旋转时则要在文本视图中减少值。最小值为0,最大值为25。
这里的RotaryKnobView类
public class RotaryKnobView extends ImageView {
private float angle = 0f;
private float theta_old=0f;
private RotaryKnobListener listener;
public interface RotaryKnobListener {
public void onKnobChanged(int arg);
}
public void setKnobListener(RotaryKnobListener l )
{
listener = l;
}
public RotaryKnobView(Context context) {
super(context);
initialize();
}
public RotaryKnobView(Context context, AttributeSet attrs)
{
super(context, attrs);
initialize();
}
public RotaryKnobView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
initialize();
}
private float getTheta(float x, float y)
{
float sx = x - (getWidth() / 2.0f);
float sy = y - (getHeight() / 2.0f);
float length = (float)Math.sqrt( sx*sx + sy*sy);
float nx = sx / length;
float ny = sy / length;
float theta = (float)Math.atan2( ny, nx );
final float rad2deg = (float)(180.0/Math.PI);
float thetaDeg = theta*rad2deg;
return (thetaDeg < 0) ? thetaDeg + 360.0f : thetaDeg;
}
public void initialize()
{
this.setImageResource(R.drawable.ic_launcher);
setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX(0);
float y = event.getY(0);
float theta = getTheta(x,y);
switch(event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_POINTER_DOWN:
theta_old = theta;
break;
case MotionEvent.ACTION_MOVE:
invalidate();
float delta_theta = theta - theta_old;
theta_old = theta;
int direction = (delta_theta > 0) ? 1 : -1;
angle += 3*direction;
notifyListener(direction);
break;
}
return true;
}
});
}
private void notifyListener(int arg)
{
if (null!=listener)
listener.onKnobChanged(arg);
}
protected void onDraw(Canvas c)
{
c.rotate(angle,getWidth()/2,getHeight()/2);
super.onDraw(c);
}
这里的主要活动类代码
final TextView tView = (TextView)findViewById(R.id.tv);
RotaryKnobView jogView = (RotaryKnobView)findViewById(R.id.knob);
jogView.setKnobListener(new RotaryKnobView.RotaryKnobListener()
{
@Override
public void onKnobChanged(int progress) {
if (progress > 0){
// rotate right
tView.setText(""+progress);
} else{
// rotate left
tView.setText(""+progress);
}
}
});
MainActivity Xml代码在这里
<com.example.ghvhjf.RotaryKnobView
android:id="@+id/knob"
android:layout_width="100dip"
android:layout_height="100dip" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
最佳答案
您的听众没有得到总进度的通知;可以看到转弯方向:
int direction = (delta_theta > 0) ? 1 : -1;
notifyListener(direction);
因此,您可以在
RotaryKnobListener
中跟踪并总结这些更改:new RotaryKnobView.RotaryKnobListener() {
private int progress = 0;
@Override
public void onKnobChanged(int direction) {
progress += direction;
progress = Math.max(0, Math.min(25, progress));
tView.setText(Integer.toString(progress));
}
}