我正在尝试填充一个微调器,但是我的String数组中出现错误,说“数组常量只能在初始化器中使用”。当我使用字符串数组作为局部变量时,我的代码工作正常,但作为全局变量,它没有。我真的需要能够将我的字符串数组用作全局变量。先感谢您。这是我的代码:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
ArrayAdapter<String> adapterdeletetype;
//createdenominationsarray = getResources().getStringArray(R.array.createdenominations); //<--works
//String [] createdenominationsarray = {"Select Portfolio", "Two", "Three"}; //<--works
createdenominationsarray = {"Select Portfolio", "Two", "Three"};// <--doesn'twork
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,createdenominationsarray){
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
denominationselection.setAdapter(adapterdeletetype);
答案 0 :(得分:1)
我为我的一个项目做了同样的事情,它对我有用。以下是供您参考的代码段。
ArrayList<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("German");
languages.add("French");
ArrayAdapter<String> langAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,languages);
ListView lv =(ListView)findViewById(R.id.listmain);
lv.setAdapter(langAdapter);
lv.setOnItemClickListener(new listclklisten(MainActivity.this));
public class listclklisten implements OnItemClickListener{
private Context parent;
public listclklisten(Context p){
parent=p;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TO DO your code here
}
}
答案 1 :(得分:1)
在string.xml
内写:
<string-array name="spinner_array_environtment">
<item>Test</item>
<item>Production</item>
</string-array>
在MainActivity.java中:
public class MainActivity extends Activity {
Spinner spinner_environment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner_environment = (Spinner) findViewById(R.id.spinnerview);
adapter =ArrayAdapter.createFromResource(this, R.array.spinner_array_environtment,R.layout.spinner_phone);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_environment.setAdapter(adapter);
}
内部spinner_phone.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13dp"
android:textColor="#4C4646" />
试一试。希望它会对你有所帮助。