0

我正在编写一个包含很多微调器的应用程序。为了使事情更简洁,我制作了一个将微调器与视图和数组适配器相关联的方法。但是,每当我尝试使用该微调器(例如设置可见性)时,都会收到空指针异常。

这是我的代码:

private void setSpinners() {
    ManureID = R.id.smanure;
    ApplicationID = R.id.sapplication;
    SlurryID = R.id.sslurry;
    MaturityID = R.id.smaturity;
    TimingID = R.id.stiming;
    SoilTypeID = R.id.ssoil;
    PreviousCropID = R.id.scropping;
    GrassRotationID = R.id.sgrassrot;
    RainID = R.id.srain;
    StrawID = R.id.sstraw;
    PID = R.id.sp;
    KID = R.id.sk;
    MgID = R.id.smg;

    // TODO update slurry values depending
    setSpinner(SlurryID, Slurry, slurrys);
    setSpinner(ApplicationID, Application, application);
    setSpinner(ManureID, Manure, manures);
    setSpinner(MaturityID, Maturity, maturity);
    setSpinner(TimingID, Timing, timing);
    setSpinner(SoilTypeID, SoilType, soilTypes);
    setSpinner(PreviousCropID, PreviousCrop, previousCrops);
    setSpinner(GrassRotationID, GrassRotation, grassRotations);
    setSpinner(RainID, Rain, rain);
    setSpinner(StrawID, Straw, straw);
    setSpinner(PID, P, p);
    setSpinner(KID, K, k);
    setSpinner(MgID, Mg, mg);
}

private void setSpinner(int ID, Spinner spinner, ArrayList<String> list) {
    spinner = (Spinner) findViewById(ID);
    ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,
            ID, list);
    spinner.setAdapter(adapt);
}

我假设该方法有问题。它实际上不是将视图与微调器正确关联吗?有没有办法修复该方法?

谢谢!

4

1 回答 1

1

你总是在这里找到setSpinner方法 中的一个微调
器 spinner = (Spinner) findViewById(ID);
. 最后,您将能够使用带有R.id.smg id 的微调器。

你需要做的是:

public void SetAllSpinners(int rootID) {
 ViewGroup vg = (ViewGroup) findViewById(rootID);
  for (int i = 0; i < vg.getChildCount(); i++) {
   View v = vg.getChildAt(i);
     /*
     Here check all the layouts that you used to contain your spinners
     */
     if(v instanceof LinearLayout || v instanceof RelativeLayout){
        SetAllSpinners(v.getId());
     }
     if (v instanceof Spinner) {
     Spinner sx = (Spinner) v;
     ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, ID,
                    list);
     sx.setAdapter(adapt);
        }
    }
}

你必须像这样调用这个方法:

SetAllSpinners(R.id.rootLayoutThatContainsYourSpinners);

设置数组适配器后,您可以在那里设置事件。请让我知道这是否有效..

于 2013-09-17T17:20:41.277 回答