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

问题描述 投票:0回答:1

我的活动中有此代码:

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)

android numberpicker
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.