将自定义数字选择器实现到活动中

时间:2014-05-10 09:32:48

标签: android numberpicker

我在活动中有这个代码:

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
        }
    });
}
}

我的自定义类的代码:

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;
}
}

问题是我不知道如何将这个号码选择器添加到活动中。换句话说,我不能让它在我的程序中工作。那么我应该如何在活动中更改我的代码来执行此操作。 据我所知,我不能使用findViewById(R.id.numberpicker1)。请帮忙。

1 个答案:

答案 0 :(得分:0)

在您的布局中,改为使用像您一样添加NumberPicker

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

您将使用指向自定义类的标记。

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

因此,如果您将此添加到activity_main布局,则可以使用View.findViewById对其进行初始化:

setContentView(R.layout.activity_main);
final MyNumberPicker np = (MyNumberPicker) findViewById(R.id.numberpicker1);