是否有可能在布局xml中填充一个旋转器的选项?这个页面建议我应该使用ArrayAdapter?不能做这件事似乎很尴尬。
我不太确定,但你可以试试。
在你的strings.xml中定义:
<string-array name="array_name"> <item>Array Item One</item> <item>Array Item Two</item> <item>Array Item Three</item> </string-array>
在你的布局中:
<Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="true" android:entries="@array/array_name" />
我听说这并不总是在设计器上工作,但它编译良好。
在你的String.xml文件中定义它,并将数组命名为你想要的,比如"Weight"
<string-array name="Weight"> <item>Kg</item> <item>Gram</item> <item>Tons</item> </string-array>
这段代码在layout。xml中
<Spinner android:id="@+id/fromspin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:entries="@array/Weight" />
在你的java文件中,getActivity用于fragment;如果你在activity中编写该代码,则删除getActivity。
getActivity
a = (Spinner) findViewById(R.id.fromspin); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.weight, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); a.setAdapter(adapter); a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (a.getSelectedItem().toString().trim().equals("Kilogram")) { if (!b.getText().toString().isEmpty()) { float value1 = Float.parseFloat(b.getText().toString()); float kg = value1; c.setText(Float.toString(kg)); float gram = value1 * 1000; d.setText(Float.toString(gram)); float carat = value1 * 5000; e.setText(Float.toString(carat)); float ton = value1 / 908; f.setText(Float.toString(ton)); } } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } }); // Inflate the layout for this fragment return v; }
关于第一条评论:如果你这样做,你会得到一个错误(在Android Studio中)。这是关于它在Android命名空间之外。如果您不知道如何修复此错误,请查看下面的示例。希望这能有所帮助!
示例-Before:
<string-array name="roomSize"> <item>Small(0-4)</item> <item>Medium(4-8)</item> <item>Large(9+)</item> </string-array>
示例—之后:
<string-array android:name="roomSize"> <item>Small(0-4)</item> <item>Medium(4-8)</item> <item>Large(9+)</item> </string-array>