質問

I have this code in activity:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final MyNumberPicker np = new MyNumberPicker(this);
    np.setOnScrollListener(new NumberPicker.OnScrollListener() {
        @Override
        public void onScrollStateChange(NumberPicker view, int scrollState) {
            if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
                np.setBottomFadingEdgeStrength(0.9f);
                np.setBottomFadingEdgeStrength(0.9f);
            } else if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE){
                np.setBottomFadingEdgeStrength(1.0f);
                np.setBottomFadingEdgeStrength(1.0f);
            }
            //also you can handle SCROLL_STATE_FLING if you want
        }
    });
}
}

And this code for my custom class:

public class MyNumberPicker extends NumberPicker {

private float bottomFadingEdgeStrength = 1.0f;
private float topFadingEdgeStrength = 1.0f;

public MyNumberPicker(Context context) {
    super(context);
}

public MyNumberPicker(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyNumberPicker(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected float getBottomFadingEdgeStrength() {
    return bottomFadingEdgeStrength;
}

@Override
protected float getTopFadingEdgeStrength() {
    return topFadingEdgeStrength;
}

void setTopFadingEdgeStrength(float strength){
    topFadingEdgeStrength = strength;
}

void setBottomFadingEdgeStrength(float strength){
    bottomFadingEdgeStrength = strength;
}
}

The thing is that I don't know how to add this number picker into activity. In other words, I can't get it to work in my program. So how should I change my code in activity to do this. As far as I can tell, I can't use findViewById(R.id.numberpicker1). Please help.

役に立ちましたか?

解決

In your layout, instead using adding a NumberPicker like you normally would:

<NumberPicker android:id="@+id/numberpicker1" ... />

You would use a tag that points to your custom class.

<your.path.to.MyNumberPicker android:id="@+id/numberpicker1" ... />

So, if you added this to your activity_main layout, you could initialize it using View.findViewById:

setContentView(R.layout.activity_main);
final MyNumberPicker np = (MyNumberPicker) findViewById(R.id.numberpicker1);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top