英文:
How can I add NumberPicker on my Layout from Java code in my Android application?
问题
我正在制作一个简单的应用程序。我想从我的Java代码中添加NumberPicker,但是当我运行它时,应用程序会立即关闭。
有人能告诉我错误出在哪里吗?
我知道我可以在XML中添加它,但我想从Java代码中添加它。
非常感谢!
package com.example.openwebpage;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
NumberPicker np;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.layout);
String[] displayed = {"1","2","3"};
np = new NumberPicker(this);
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
np.setLayoutParams(layoutParams);
np.setDisplayedValues(displayed);
np.scrollBy(0,3);
np.setMinValue(0);
np.setMaxValue(3);
np.setWrapSelectorWheel(true);
layout.addView(np);
}
}
英文:
I am making a simple application. I want to add NumberPicker from my Java code, but when I run it, the applications closes immediately.
Can someone tell me where is the error?
I know that I can add it in XML, but I wanted to add it from Java code.
Thanks a lot
package com.example.openwebpage;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
NumberPicker np;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.layout);
String[] displayed = {"1","2","3"};
np = new NumberPicker(this);
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
np.setLayoutParams(layoutParams);
np.setDisplayedValues(displayed);
np.scrollBy(0,3);
np.setMinValue(0);
np.setMaxValue(3);
np.setWrapSelectorWheel(true);
layout.addView(np);
}
}
答案1
得分: 0
你需要更新这段代码片段:
np.scrollBy(0,2);
np.setMinValue(0);
np.setMaxValue(2);
异常是由于 setMaxValue(3) 导致的数组索引越界。
英文:
You need to update this code snippet:
np.scrollBy(0,2);
np.setMinValue(0);
np.setMaxValue(2);
The exception was Array Indexed Out of bound due to setMaxValue(3).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论