简单来说,我创建了一个微调器。我的array.xml
中有微调项和项的值。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="select">
<item>a</item>
<item>b</item>
<item>c</item>
</string-array>
<integer-array name="selectValues">
<item>1</item>
<item>2</item>
<item>3</item>
</integer-array>
</resources>
这也是我的
linearlayout
。<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/selectLayout"
>
<TextView
android:id="@+id/tvSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/select"
android:textSize="18sp"
android:layout_gravity="center"
/>
<Spinner
android:id="@+id/sSelect"
android:layout_width="179dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:entries="@array/select"
android:prompt="@string/sec"
android:spinnerMode="dialog"
/>
</LinearLayout>
在我的活动中,我创建了
OnItemSelectedListener
,当用户选择了一个项目时,我想更改TextView
。我认为使用开关时有问题。这是活动。
public class Select extends Activity implements OnItemSelectedListener{
int[] itemValues;
TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Resources rsc = getResources();
itemValues = rsc.getIntArray(R.array.selectValues);
t = (TextView) findViewById(R.id.tvSelect);
setContentView(R.layout.select);
Spinner form = (Spinner) findViewById(R.id.sSelect);
form.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> item, View which, int sort,
long arg3) {
// TODO Auto-generated method stub
switch(which.getId())
{
case R.id.sSelect:
int value = itemValues[sort];
t.setText(value);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
如何解决?
编辑:当我尝试删除开关时,出现
unfortunately has stopped
错误。 最佳答案
正如Spring Breaker所说的,您需要在调用setContentView()
之前先调用findViewById()
。如果首先调用findViewById()
,它将返回null,当您尝试使用NullPointerException
时将得到一个TextView
。
在onItemSelected()
中,which
实际上不是对Spinner
的引用。它是对Spinner
的子视图的引用,该子视图保存了用户按下的特定项目。您需要切换第一个参数AdapterView<?>
。setText()
期望引用XML字符串的String
或int
资源值。您将其传递为int
,而不是资源值,因此它将无法正常工作。这是一个快速的解决方法:
String value = String.valueOf(itemValues[position]);
t.setText(value);