我在一些网站上进行了评价,但我无法理解如何从旋钮获得价值。鉴于下面我尝试了示例代码。我需要的是当旋转右侧旋钮时我希望增加文本视图中的值同时左侧旋转意味着减少文本视图中的值。最小值为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" />
答案 0 :(得分:1)
您的听众并未了解总进度;关于转弯方向,如下所示:
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));
}
}