gpt4 book ai didi

Android - 以编程方式将文本从 strings.xml 添加到 TextView

转载 作者:行者123 更新时间:2023-11-30 03:12:53 29 4
gpt4 key购买 nike

好的,所以我一直在学习教程 ( http://javatechig.com/android/android-spinner-example ),它是关于创建 Spinners 和动态添加图像(其位置在 strings.xml 文件中定义)到 View 。嗯,这很好,但我想扩展项目,以便我可以包含文本数组,再次在 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) {

}

});
}

最佳答案

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 对象中

text.setText(textString[i]); // at position i

关于Android - 以编程方式将文本从 strings.xml 添加到 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641187/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com