好的,所以我一直在关注一个教程(http://javatechig.com/android/android-spinner-example),该教程是关于创建Spinners并动态地将图像(其位置在strings.xml文件中定义)添加到视图中。那么工作正常,但我想扩展项目,以便我可以包含在strings.xml文件中再次定义的文本数组,以便在图像之前和之后出现。 我的代码如下,正如您所看到的,我想用2个setText行替换我已经选择的微调项目的引用。 有任何想法吗?谢谢你的兴趣。
感谢大家的投入,我现在已经解决了问题,并在下面显示了一些注释代码,我是如何解决的......
public class MainActivity extends Activity {
private ImageView image;
private String[] states;
private Spinner spinner1;
private TypedArray imgs;
private String[] leaders;
private String[] descrip;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
states = getResources().getStringArray(R.array.countries);
imgs = getResources().obtainTypedArray(R.array.leader_photos);
// --- The following lines grab the problematic string arrays defined in
// strings.xml
leaders = getResources().getStringArray(R.array.leaders);
descrip = getResources().getStringArray(R.array.descrip);
image = (ImageView) findViewById(R.id.leaderPhoto);
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// The variable index identifies what position the selected
// spinner is. TextView text... locks to the TextView defined in
// the activity_main.xml layout file. text.setText... loads the
// appropriate value from the leaders string array
int index = parent.getSelectedItemPosition();
TextView text = (TextView) findViewById(R.id.tv1);
text.setText(leaders[index]);
image.setImageResource(imgs.getResourceId(
spinner1.getSelectedItemPosition(), -1));
// See earlier comments above TextView tv1 for how this works
TextView text2 = (TextView) findViewById(R.id.tv2);
text2.setText(descrip[index]);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
答案 0 :(得分:1)
Android - 以编程方式将strings.xml中的文本添加到TextView -
如果我理解你的话?
Resources resources = context.getResources();
String[] textString = resources.getStringArray(R.array.mytext);
然后你有一个字符串向量中的文本 - 很容易放入textView
然后在xml文件中
<string-array name = "mytext">
<item> ... text </item>
<item> ... text</item>
<item> ... text</item>
</string-array>
在textView-object
中text.setText(textString[i]); // at position i
答案 1 :(得分:0)
您可以使用您进入Spinner的OnClickListener的位置来获取该状态的特定领导者和描述,如下所示。 text.setText(前导[位置]); text2.setText(记述[位置]);