使用xml资源创建ArrayAdapter并检索"id".或“价值"使用微调器的字段 [英] Creating ArrayAdapter using xml resource and retrieving "id" or "value" fields using spinner
本文介绍了使用xml资源创建ArrayAdapter并检索"id".或“价值"使用微调器的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个微调器,使用ArrayAdapter从资源xml填充其微调器的值.
I am trying to create a spinner, the values of which I am populating from a resource xml, using ArrayAdapter.
我也想给资源项一些"id"或"value".我如何在onItemSelected()回调中检索这些值?
I also want to give the resource items some "id" or "value". How can i retrieve these values inside the onItemSelected() callback ?
这是Java代码.
package com.waus.waus;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class Register extends Activity implements OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Spinner countrySpinner = (Spinner) findViewById(R.id.country_code_spinner);
ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(this, R.array.country_codes, android.R.layout.simple_spinner_item);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countrySpinner.setOnItemSelectedListener(this);
countrySpinner.setAdapter(countryAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(this, "THIS IS WHERE I WANT TO SHOW THE ID/VALUE" ,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
这是我要使用的XML文件.
This is the XML file I want to use.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="country_codes">
<item value="91">India</item>
<item value="1">United States</item>
// OR
<item id="1">United States</item>
</string-array>
</resources>
如何在不使用2个资源文件的情况下完成此操作.即,一个用于代码,另一个用于名称.
How can it be done without using 2 resource files. i.e. one for codes and another for names.
推荐答案
String[] SortByField= activity.getResources().getStringArray(
R.array.country_codes);
或
Arrayadapter adapterFillClass = ArrayAdapter.createFromResource(activity,
R.array.country_codes,
android.R.layout.simple_spinner_dropdown_item);
spinner.setadapter(adapterFillClass);
我希望它对您有用.
这篇关于使用xml资源创建ArrayAdapter并检索"id".或“价值"使用微调器的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文