Android中如何调用String-array

在Android开发中,我们经常会遇到一些列表的创建,在这之中,就需要调用String-array,这样就会使得程序更加简洁。具体使用方法如下:

1、在layout文件夹下创建String.xml文件,代码如下:




    Happyidom
    Settings
    Hello world!
    MainActivity
    StudyActivity
    学习
    搜搜
    游戏
    收藏
    帮助


    动物类
    自然类
    人物类
    季节类
    数学类
    寓言类
    其他类
       


2、 然后在StudyActivity通过以下方式即可获取到 name 为category 数组集下的所有数据
package cn.bzu.zyw.happyidiom.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import cn.bzu.zyw.happyidiom.R;
import cn.bzu.zyw.happyidiom.adapter.CategoryAdapter;
import cn.bzu.zyw.happyidiom.entity.Category;
public class StudyActivity extends Activity{
	private List categoryList;
	private String[] category_names;
	private int[] category_images;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_study);
		initCategories();//初始化类别
		CategoryAdapter adapter=new CategoryAdapter(this,
				R.layout.category_item, categoryList);
		ListView listView=(ListView)findViewById(R.id.IvCategories);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterViewadapterView,View view,
					   int position,long id){
				switch (position) {
				case 0:
					Intent intent=
					new Intent(StudyActivity.this,StudyAnimalActivity.class);
					startActivity(intent);
					break;
				default:
					break;
				}
				Category category=categoryList.get(position);
				Toast.makeText(StudyActivity.this, category.getName(), 
						Toast.LENGTH_LONG).show();
			}
		});
	}
	private void initCategories(){
		categoryList=new ArrayList();
		Resources resources =getResources();
		category_names=resources.getStringArray(R.array.category);
     	category_images=new int[] {R.drawable.category_animal,
				R.drawable.category_nature,R.drawable.category_human,
				R.drawable.category_season,R.drawable.category_number,
				R.drawable.category_fable,R.drawable.category_other};
		for(int i=0;i

通过

Resources resources =getResources();
		category_names=resources.getStringArray(R.array.category);
来实现String-array的调用。


你可能感兴趣的:(Android)