0

我正在尝试让我的 Spinner1 更改 spinner2 上的可见性。我的代码编译正常,但应用程序在打开时崩溃。

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Spinner spinner = (Spinner)findViewById(R.id.spinner2);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {

        public void onNothingSelected(AdapterView<?> arg0) {

        }

        public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
            Spinner spinner = (Spinner)findViewById(R.id.spinner2);
            Spinner spinner1 = (Spinner)findViewById(R.id.spinner1);
            TextView textview1 = (TextView)findViewById(R.id.textView1);

            if (spinner.getSelectedItemPosition() == 1) {
                textview1.setVisibility(View.VISIBLE);
                spinner1.setVisibility(View.VISIBLE);
            }
        }
    });
}
4

2 回答 2

0

好的,所以我使用一个类来检查所选项目,修复了初始应用程序崩溃

主要代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Spinner spinner = (Spinner)findViewById(R.id.spinner2);
    spinner.setOnItemSelectedListener(new checkSelectedItem());
}

我的课:

public class checkSelectedItem implements OnItemSelectedListener {

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    Spinner spinner1 = (Spinner)parent.findViewById(R.id.spinner1);
    TextView textview1 = (TextView)parent.findViewById(R.id.textView1);
    if (pos == 1) {
        textview1.setVisibility(View.VISIBLE);
        spinner1.setVisibility(View.VISIBLE);
    }
    else {
        if ( textview1.getVisibility() == View.VISIBLE) {
            textview1.setVisibility(View.INVISIBLE);
        }
        if ( spinner1.getVisibility() == View.VISIBLE) {
            spinner1.setVisibility(View.INVISIBLE);
        }
    }
}

public void onNothingSelected(AdapterView parent) {

}

所以最初的崩溃是固定的,但是现在当我在我的 spinner2 中选择选项 1 时,应用程序崩溃了..

于 2012-11-15T00:04:11.660 回答
0

请不要在活动期间设置ID;它根本不好;这样做:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Spinner spinner = (Spinner)findViewById(R.id.spinner2);
    Spinner spinner1 = (Spinner)findViewById(R.id.spinner1);
    TextView textview1 = (TextView)findViewById(R.id.textView1);


    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {

        public void onNothingSelected(AdapterView<?> arg0) {

        }

        public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
            if (spinner.getSelectedItemPosition() == 1) {
                textview1.setVisibility(View.VISIBLE);
                spinner1.setVisibility(View.VISIBLE);
            }
        }
    });}
于 2012-11-14T07:02:04.990 回答