gpt4 book ai didi

java - 如何从android中的string.xml文件获取字符串资源

转载 作者:行者123 更新时间:2023-12-01 12:20:52 25 4
gpt4 key购买 nike

我正在使用以下代码。尽管代码运行良好。我想从 string.xml 文件获取字符串而不在 Java 代码中初始化字符串?我不知道该怎么做。我还想进行以下操作:在特定列表项上单击它会启动新 Activity 吗?

package com.example.listviewexample;
import java.util.Arrays;
import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

final List<String> elements = Arrays.asList("Element 1", "Element 2", "Element 3",
"Element 4", "Element 5");

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.activity_main,elements);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}``
});
}
}

最佳答案

将数组定义到 arrays.xml

<?xml version="1.0" encoding="utf-8"?>  
<resources>
<array name="myArray">
<item>Element 1</item>
<item>Element 2</item>
<item>Element 3</item>
<item>Element 4</item>
<item>Element 5</item>
</array>
</resources>

加载元素:

String[] elements = getResources().getStringArray(R.array.myArray);  
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_main,elements);

关于java - 如何从android中的string.xml文件获取字符串资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26659069/

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