改变微调运行时(android)的内容,尝试和失败

时间:2012-02-02 07:54:44

标签: android android-widget android-spinner

我最近发布了一个关于如何在程序执行期间更改微调器的值的问题,并被告知更改用于生成适配器的数组并调用notifyDataSetChanged();

我尝试了但是我的微调器没有得到更新,即使我的阵列是。我附上以下代码

 public void onCreate(Bundle savedInstanceState) 
    {
    res=getResources();
    Boolean a;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

// First spinner whose value determines the value of the second spinner        
    spinner = (Spinner) findViewById(R.id.spinner1); 
// ArrayAdaptor of first spinner
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this                            R.array.planets_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    spinner2.setVisibility(4);// spinner 2 is not visible initially
// ArrayAdaptor of first spinner        
    adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinner_drop);
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner2.setAdapter(adapter2);

    Context context = getApplicationContext();
    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
    }
public class MyOnItemSelectedListener implements OnItemSelectedListener 
{

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
    {
        if(pos!=0)
        {

     //copying string array of second spinner from strings.xml to the current string array
      spinner_drop=res.getStringArray(R.array.activities_array2);
      Toast.makeText(parent.getContext(), "The planet is " +spinner_drop[0] , Toast.LENGTH_SHORT).show(); //this toast shows up
      adapter2.notifyDataSetChanged();
      spinner2.refreshDrawableState();
      spinner2.setVisibility(0);//this command works and the spinner is visible, but it is empty
        }
    }

    public void onNothingSelected(AdapterView parent) 
    {
      // Do nothing.
    }


}

任何想法都有所帮助。

PS:我试过删除整个看不见的,可见的东西,没有帮助

提前致谢

1 个答案:

答案 0 :(得分:0)

按如下方式修改onItemSelected方法,请注意我在下面添加的新添加

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
  if (pos!=0) {

    //copying string array of second spinner from strings.xml to the current
    //string array
    spinner_drop=res.getStringArray(R.array.activities_array2);
    Toast.makeText(parent.getContext(), "The planet is " +spinner_drop[0],
                   Toast.LENGTH_SHORT).show(); //this toast shows up
    adapter2.notifyDataSetChanged();
    spinner2.setAdapter(adapter2); // <--- New Addition
    // spinner2.refreshDrawableState();
    spinner2.setVisibility(0); //this command works and the spinner is visible,
                               //but it is empty
  }
}