我有以下代码:
public class OnboardingActivity extends BaseLoggedInActivity
implements CountryPickerDialog.ICountryPickerDialogUsers, AdapterView.OnItemSelectedListener {
private Spinner _countryCodeSpinner;
.
.
.
private void setupCountrySpinner() {
List<String> sortedCountryCodeList = CountryData.getInstance().getSortedCountryCodes();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
R.layout.country_code_spinner_item,
sortedCountryCodeList);
_countryCodeSpinner.setOnItemSelectedListener(this);
_countryCodeSpinner.setAdapter(adapter);
_countryCodeSpinner
.setOnTouchListener(getCountryCodeSpinnerTouchListener(_countryCodeSpinner));
int position = getDefaultCountryNamePosition();
if (position >= 0) {
_countryCodeSpinner.setSelection(position);
}
}
.
.
.
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
_logger.debug("Inside onItemSelected");
view.setSelected(true);
}
我在上面的函数 onItemSelected 中得到一个空指针异常。它返回NULL视图。这个跟踪我从一个用户收到,但我无法自己重现。可能有什么理由使用NULL视图调用onItemSelected?
由于
答案 0 :(得分:2)
很晚了答案我仍然不知道它是怎么发生的,但是您需要在
中更改view :View
@Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { _logger.debug("Inside onItemSelected"); view.setSelected(true); }
当视图不可用时,view:View?
可以为 null
答案 1 :(得分:0)
可能是在更改配置后引起的,例如旋转设备。重新创建了微调器,并且在onItemSelected回调中收到空参数。
您可以将实现中的视图注释为@nullable,然后
if (view != null) {view.setSelected(true);}
如果您使用的是Kotlin,请尝试以下操作:
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long){
view?.isSelected = true
}
答案 2 :(得分:0)
您可以通过旋转阻止可能为空视图的默认选择,然后显式执行setSelection()
:
int position = getDefaultCountryNamePosition();
if (position < 0) {
position = 0;
}
// Block default selection to custom onItemSelected() from listener initialization
//, see https://stackoverflow.com/a/37561529/1074998
// + 1 as fake value because onItemSelected() only triggered by setSelection() if different value.
_countryCodeSpinner.setSelection(position + 1, false);
_countryCodeSpinner.setOnItemSelectedListener(this);
// position(without + 1) is our real target.
// set selection explicitly should not null now
_countryCodeSpinner.setSelection(position, false);
请注意,如果您在 onItemSelected() 中更改 UI,则简单地捕获 null 会导致问题,因为布局已经刷新。