相关疑难解决方法(0)

Android Spinner:在初始化期间避免onItemSelected调用

我用a Spinner和a 创建了Android应用程序TextView.我的任务是在TextView的Spinner下拉列表中显示所选项目.我在onCreate方法中实现了Spinner,所以当我运行程序时,它会显示一个值TextView(在从下拉列表中选择一个项目之前).

我只想在从下拉列表中选择一个项目后才在TextView中显示该值.我该怎么做呢?

这是我的代码:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class GPACal01Activity extends Activity implements OnItemSelectedListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

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

        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.noofsubjects_array, android.R.layout.simple_spinner_item);
        // Specify the layout …
Run Code Online (Sandbox Code Playgroud)

android android-layout android-spinner

134
推荐指数
9
解决办法
8万
查看次数

Android NullPointerException - 旋转后,Spinner onItemSelected`view`参数为null

注意:来自另一个类似SO问题的答案的限制性解决方法对我有用,但我有兴趣找到一个真正的解决方案.解决方法是将此添加到我的Activity:

@Override  
protected void onSaveInstanceState(Bundle outState) { /* do nothing */ }
Run Code Online (Sandbox Code Playgroud)

但我仍然希望将这个问题保持开放,以期找到更好的解决方案.


我的应用程序在最新的Android(Marshmallow,Lollipop)上旋转时崩溃,但它适用于KitKat.在Spinner onClick方法中,我得到了父元素的第一个子元素,它是下拉列表中的第一个textview(也就是微调器).当我不旋转它时,它工作得很好.此外,当我注释掉抛出NullPointerException的那一行时,它也可以正常工作.所以这是问题的唯一原因.

我知道它是空的,但我不明白为什么,或者如何解决它?此外,请注意我不能使用XML,因为文本颜色仅在运行时动态知道.另外,我希望最小API为15.

我加了一些调试代码,并且发现了旋转之前,parentview参数都不能为空.但旋转后,view为空.(但parent仍然不是空的).

请参阅具有空指针异常的行的******:

private void setUpSpinner(int accentColor, final int backgroundColor, Toolbar toolbar)
{
    Spinner spinner = (Spinner) findViewById(R.id.spinner);

    //Get rid of the normal toolbar's title, because the spinner is replacing the title.
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    //Set the choices on the spinner by setting the adapter.
    spinner.setAdapter(new SpinnerAdapter(toolbar.getContext(), new String[]{"Overview", "Story", "Specifications", "Poll", "Video"},
            accentColor, backgroundColor));

    //Set …
Run Code Online (Sandbox Code Playgroud)

android nullpointerexception

6
推荐指数
1
解决办法
2478
查看次数