如何在Android应用程序中使用string.xml文件值

时间:2011-12-17 23:11:58

标签: android android-layout

这是代码..

string.xml

<?xml version="1.0" encoding="utf-8" ?> 
- <resources>
- <string-array name="countries_array">
  <item>Bahrain</item> 
  <item>Bangladesh</item> 
  <item>Barbados</item> 
  <item>Belarus</item> 
  <item>Belgium</item> 
  <item>Belize</item> 
  <item>Benin</item> 
  </string-array>
  </resources>

布局

list_item.xml

<?xml version="1.0" encoding="utf-8" ?> 
  <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:textSize="16sp" />

main.xml中

<?xml version="1.0" encoding="utf-8" ?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> 
  </LinearLayout>

.java文件

package examples.com;

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 HelloListViewActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      String[] countries = getResources().getStringArray(R.array.countries_array);
      setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));

      ListView lv = getListView();
      lv.setTextFilterEnabled(true);

      lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
        }
      });
    }
} 

这是在xml文件中生成某些名称的动态列表的代码。它将名称列表作为xml文件的输入并显示为dyanamicaly。从xml文件中获取数据时,我收到未定义符号的错误as-

error is in this line

      String[] countries = getResources().getStringArray(R.array.countries_array);

cant find symbol array in R.

countries_array is in string.xml file. If this method of accessing it is wrong then how to access it?
Thanx in advance.

1 个答案:

答案 0 :(得分:2)

将您的数组声明放入arrays.xml目录中标题为res/values的文件中。当您尝试键入R.array.countries_array作为资源标识符时,系统正在查看此位置。换句话说,

<强> RES /值/ arrays.xml

<?xml version="1.0" encoding="utf-8" ?> 
<resources>
  <string-array name="countries_array">
    <item>Bahrain</item> 
    <item>Bangladesh</item> 
    <item>Barbados</item> 
    <item>Belarus</item> 
    <item>Belgium</item> 
    <item>Belize</item> 
    <item>Benin</item> 
    </string-array>
</resources>

HTH!