我在我的代码中使用Spinner控件.我希望在选择时突出显示该项目(即,该项目的背景颜色已更改).怎么能实现这一目标?
注意:来自另一个类似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.
我加了一些调试代码,并且发现了旋转之前,parent和view参数都不能为空.但旋转后,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)