如何以编程方式填充微调器选项(不使用xml)

时间:2017-06-11 20:23:44

标签: android spinner

我希望使用程序代码设置微调器项目,而不是在xml布局中使用android:entries。 但我没有这样做。 我想根据条件设置微调器项目,所以不能静态地使用xml设置它,所以请帮助我动态设置。 这是代码: public class Converter扩展AppCompatActivity {

EditText et2;
TextView tv;
Spinner spr2,spr3;
ArrayAdapter adap2,adap3;
String []spr_2;
String []spr_3;
Button btn2;
String s1;


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

    et2=(EditText) findViewById(R.id.et2);
    tv=(TextView) findViewById(R.id.tv);
    spr2=(Spinner) findViewById(R.id.spr2);
    spr3=(Spinner) findViewById(R.id.spr3);
    btn2=(Button) findViewById(R.id.btn2);

    Bundle b=getIntent().getExtras();
    et2.setText(b.getString("Value1"));
    s1=b.getString("SpinnerValue");
    adap2=adap3=new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line);

    if(s1 == "height") {
        spr_2 = spr_3 = getResources().getStringArray(R.array.height);
        adap2 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, spr_2);
        adap3 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, spr_3);
        spr2.setAdapter(adap2);
        spr3.setAdapter(adap3);
    }
    if(s1 == "weight") {
        spr_2 = spr_3 = getResources().getStringArray(R.array.weight);
        adap2 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, spr_2);
        adap3 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, spr_3);
        spr2.setAdapter(adap2);
        spr3.setAdapter(adap3);
    }
    if(s1 == "distance") {
        spr_2 = spr_3 = getResources().getStringArray(R.array.distance);
        adap2 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, spr_2);
        adap3 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, spr_3);
        spr2.setAdapter(adap2);
        spr3.setAdapter(adap3);
    }
    if(s1 == "currency") {
        spr_2 = spr_3 = getResources().getStringArray(R.array.height);
        adap2 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, spr_2);
        adap3 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, spr_3);
        spr2.setAdapter(adap2);
        spr3.setAdapter(adap3);
    }






}

}

1 个答案:

答案 0 :(得分:0)

看起来if-blocks中的代码没有被调用。你不应该像这样检查对象的平等性。运营商&= 39; =='检查身份,而不是平等。不是s1 == s2,而是s1.equals(s2),甚至更好的Objects.equals(s1,s2)。 您的代码应如下所示:

String[] items;
if ("height".equals(s)) 
    items = getResources().getStringArray(R.array.height);
else if ("width".equals(s)) 
    items = getResources().getStringArray(R.array.width);
....
else
    items = getResources().getStringArray(R.array.width); //just for example

spinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, items));