旋转应用程序崩溃打开。

时间:2012-11-14 06:02:26

标签: android android-layout android-spinner

我正在尝试让我的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);
            }
        }
    });
}

2 个答案:

答案 0 :(得分:1)

请不要在活动期间设置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);
            }
        }
    });}

答案 1 :(得分: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时,应用程序崩溃..