Android小程序——乐学成语实现(四)

在第三阶段中,我们要以列表的形式显示出成语的分类列表

首先我们要准备好一组图片,修改values中的string.xml文件,代码如下:

	<span style="font-size:14px;"><string-array name="category">
	    <item>动物类</item>
	    <item>自然类</item>
	    <item>人物类</item>
	    <item>季节类</item>
	    <item>数字类</item>
	    <item>寓言类</item>
	    <item>其他类</item>
	</string-array></span>

接着定义一个实体类,作为ListView适配器的适配类型,在entity包下新建类Category,代码如下:

<span style="font-size:14px;">public class Category {

	private String name;//类别名称
	private int imageId;//类别对应的图片
	
	public Category(String name, int imageId) {
		super();
		this.name = name;
		this.imageId = imageId;
	}

	public String getName() {
		return name;
	}
	
	public int getImageId() {
		return imageId;
	}
}</span>

Category类中只有两个字段,name表示种类的名字,imageId表示类别对应图片的资源id,在layout下新建activity_study.xml文件,主要添加了一个ListView控件,代码如下:

<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="@drawable/bg_ling"
    tools:context=".StudyActivity">
    <ListView 
        android:id="@+id/lvCategories"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true">
    </ListView>
</RelativeLayout></span>

然后需要为ListView的子项指定一个我们自定义的布局,在layout目录下新建category_item.xml,代码如下:

<span style="font-size:14px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="horizontal" >
    <ImageView 
        android:id="@+id/category_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/category_animal"/>
	<TextView 
	    android:id="@+id/category_name"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="@array/category"
	    android:gravity="center"
	    android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout></span>

在这个布局中,我们定义了一个ImageView用于显示类别的图片,又定义了一个TestView用于显示类别的包名。

接下来组要在应用的包下创建adapter包,在该包下创建一个自定义的适配器,这个适配器继承自ArrayAdapter,并将泛型指定为Category类。新建类CategoryAdapter,代码如下:

<span style="font-size:14px;">public class CategoryAdapter extends ArrayAdapter<Category> {
	private int resourceId;

	public CategoryAdapter(Context context, int resource, List<Category> objects) {
		super(context, resource, objects);
		resourceId = resource;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Category category = getItem(position);// 获取当前项的Category实例
		View view = LayoutInflater.from(getContext()).inflate(resourceId, null);
		ImageView caImageImage = (ImageView) view.findViewById(R.id.category_image);
		TextView categoryName = (TextView) view.findViewById(R.id.category_name);
		categoryImage.setImageResource(category.getImageId());
		categoryName.setText(category.getName());
		return view;
	}
}</span>

接下来在activity包下新建StudyActivity继承自Activity,代码如下:

<span style="font-size:14px;">public class StudyActivity extends Activity {
	private List<Category> categoryList;
	private String[] category_names;
	private int[] category_images;

	@Override
	protected void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		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);
	}

	private void initCategories() {
		categoryList = new ArrayList<Category>();
		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 < category_names.length; i++) {
			categoryList.add(new Category(category_names[i], category_images[i]));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.study, menu);
		return true;
	}
}</span>

在修改AndroidMainifest.xml文件,将StudyActivity变为入口类,代码如下:

<span style="font-size:14px;"><activity
            android:name="cn.edu.bztc.happyidiom.activity.StudyActivity"
            android:label="@string/title_activity_main" >
</activity></span>

运行结果如下:


进一步优化,在CategoryAdapter中修改代码:

<span style="font-size:14px;">public class CategoryAdapter extends ArrayAdapter<Category>{
	private int resourceId;
	public CategoryAdapter(Context context,int resource,List<Category> objects){
		super(context, resource, objects);
		resourceId=resource;
	}
	@Override
	public View getView(int position,View convertView,ViewGroup parent){
		Category category = getItem(position);//获取当前项的Category实例
		View view;
		ViewHolder viewHolder; 
		if(convertView ==null){
			view = LayoutInflater.from(getContext()).inflate(resourceId, null);
			viewHolder = new ViewHolder();
			viewHolder.categoryImage = (ImageView) view.findViewById(R.id.category_image);
			viewHolder.cayegoryName = (TextView) view.findViewById(R.id.category_name);
			view.setTag(viewHolder);//将ViewHolder储存在View中
		}else{
			view = convertView;
			viewHolder = (ViewHolder) view.getTag();//重新获取ViewHolder
		}
		viewHolder.categoryImage.setImageResource(category.getImageId());
		viewHolder.cayegoryName.setText(category.getName());
		return view;
	}
	class ViewHolder{
		ImageView categoryImage;
		TextView cayegoryName;
	}
}</span>

修改StudyActivity中的代码:

<span style="font-size:14px;">public class StudyActivity extends Activity{
	private List<Category> 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.lvCategories);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapterView,View view,int position,long id){
				Category category = categoryList.get(position);
				Toast.makeText(StudyActivity.this, category.getName(), Toast.LENGTH_LONG).show();
			}
		});
	}
……
}</span>

运行结果如图:




不过如果点击每一项的时候,选中的项会出现橙色的背景,修改activity_study.xml文件就会去掉,代码如下:

<span style="font-size:14px;"><span style="font-size:14px;">android:listSeletor="#00000000"</span></span>

界面载入的过程有些生硬,下面我们为界面增加淡入淡出的动画效果。

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromAlpha="0.0"
    android:toAlpha="1.0" >
</alpha>

设置了一个Alpha动画,从有到无的过程。创建anim_layout_listview.xml文件,代码如下:

<span style="font-size:14px;"><layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android" 
    android:animation="@anim/anim_listview"
    android:animationOrder="random"
    android:delay="0.2">
</layoutAnimation></span>

接下来修改MainActivity,代码如下:

<span style="font-size:14px;">public class MainActivity extends TabActivity {

	private TabHost tabHost;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 取消标题栏
		setContentView(R.layout.activity_main);
		tabHost = getTabHost();
		addTab("study", R.string.title_study, R.drawable.study, StudyActivity.class);
		addTab("search", R.string.title_search, R.drawable.search, StudyActivity.class);
		addTab("game", R.string.title_game, R.drawable.game, StudyActivity.class);
		addTab("save", R.string.title_save, R.drawable.save, StudyActivity.class);
		addTab("help", R.string.title_help, R.drawable.search, StudyActivity.class);
	}
	private void addTab(String tag, int title_introduction, int title_icon,
			Class ActivityClass) {
		tabHost.addTab(tabHost
				.newTabSpec(tag)
				.setIndicator(getString(title_introduction),
						getResources().getDrawable(title_icon))
				.setContent(new Intent(this,ActivityClass)));
	}
	public boolean onCreateOptionsMenu(Menu menu){
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}</span>

通过Intent,将选项卡和对应的StudyActivity关联起来了

在layout下新建activity_animal.xml文件,代码如下:

<span style="font-size:14px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_animal"
    android:orientation="vertical" >

    <ListView 
        android:id="@+id/lvAnimalList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layoutAnimation="@anim/anim_layout_listview"
        android:listSelector="#00000000"
        ></ListView>
</LinearLayout></span>

然后在layout目录下新建animal_item.xml文件,代码如下:

<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:padding="10dp"
    >
    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:text="助人为乐"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
        <ImageButton 
            android:id="@+id/btnSave"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/tvName"
            android:src="@drawable/btnsave"/>
</RelativeLayout></span>

接下来创建adapter包,添加自定义适配器,这个适配器继承自ArrayAdapter,并将泛型指定为Animal类,新建AnimalAdapter,代码如下:

<span style="font-size:14px;">public class AnimalAdapter extends ArrayAdapter<Animal>{
	private int resourceId;
	public AnimalAdapter(Context context, int resource,
			List<Animal> objects) {
		super(context, resource, objects);
		resourceId = resource;
	}
	
	@Override
	public View getView(int position,View convertView,ViewGroup parent){
		final Animal animal = getItem(position);//获取当前的Animal实例
		View view;
		ViewHolder viewHolder;
		if(convertView == null){
			view = LayoutInflater.from(getContext()).inflate(resourceId, null);
			viewHolder = new ViewHolder();
			viewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
			viewHolder.btnSave = (ImageButton) view.findViewById(R.id.btnSave);
			view.setTag(viewHolder);//将ViewHolder储存在View中
		}else{
			view = convertView;
			viewHolder = (ViewHolder) view.getTag();//重新获取ViewHolder 
		}
		viewHolder.tvName.setText(animal.getName());
		return view;
	}
	class ViewHolder{
		TextView tvName;
		ImageButton btnSave;
	}
}</span>

下面在activity包下新建AtudyAnimalActivity继承自Activity,代码如下:

<span style="font-size:14px;">public class StudyAnimalActivity extends Activity {
	private List<Animal> animalList;
	private AnimalDao animalDao;
	private ListView lvAnimalList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_animal);
		initAnimals();
		lvAnimalList = (ListView) findViewById(R.id.lvAnimalList);
		AnimalAdapter animalAdapter = new AnimalAdapter(this,
				R.layout.animal_item, animalList);
		lvAnimalList.setAdapter(animalAdapter);
	}

	private void initAnimals() {
		animalDao = AnimalDao.getInstance(this);
		animalList = animalDao.getAllAnimals();
	}
}</span>

接下来修改StudyActivity中的点击事件,代码如下:

<span style="font-size:14px;">public void onItemClick(AdapterView<?> adapterView,View view,int position,long id){
				<strong>switch(position){
				case 0:
					Intent intent=new Intent(StudyActivity.this,StudyAnimalActivity.class);
					startActivity(intent);
				break;
				default:
					break;
				}</strong>
				Category category = categoryList.get(position);
				Toast.makeText(StudyActivity.this, category.getName(), Toast.LENGTH_LONG).show();
			}
		});</span>

修改AnimalManifest.xml文件,将StudyActivity变为入口类,运行如图:


接下来我们设置收藏按钮,修改AnimalAdapter类,代码如下:

<span style="font-size:14px;">public class AnimalAdapter extends ArrayAdapter<Animal>{
	<strong>private Context context;</strong>
	public AnimalAdapter(Context context, int resource,
			List<Animal> objects) {
		super(context, resource, objects);
		<strong>this.context=context;</strong>
		resourceId = resource;
	}
	private int resourceId;
	
	@Override
	public View getView(int position,View convertView,ViewGroup parent){
		<strong>final Animal animal = getItem(position);//获取当前的Animal实例</strong>
		View view;
		ViewHolder viewHolder;
		if(convertView == null){
			view = LayoutInflater.from(getContext()).inflate(resourceId, null);
			viewHolder = new ViewHolder();
			viewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
			viewHolder.btnSave = (ImageButton) view.findViewById(R.id.btnSave);
			viewHolder.btnSave.setFocusable(false);
			viewHolder.btnSave.setFocusableInTouchMode(false);
			<strong>viewHolder.btnSave.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					Toast.makeText(context, "你要收藏"+animal.getName()+"吗",Toast.LENGTH_SHORT).show();
				}
			});</strong>
			view.setTag(viewHolder);//将ViewHolder储存在View中
		}else{
			view = convertView;
			viewHolder = (ViewHolder) view.getTag();//重新获取ViewHolder 
		}
		viewHolder.tvName.setText(animal.getName());
		return view;
	}
	class ViewHolder{
		TextView tvName;
		ImageButton btnSave;
	}
}</span>

运行结果:


显示每条成语的详细信息,在layout下新建布局文件dialog_info.xml,代码如下:

<span style="font-size:14px;">public class StudyAnimalActivity extends Activity {
	……
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_animal);
		……
		<strong>lvAnimalList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long id) {
				Animal animal = animalList.get(position);
				String result = animal.getName() + "\n" + animal.getPronounce()
						+ "\n【解释】:" + animal.getExplain() + "\n【近义词】:"
						+ animal.getHomoionym() + "\n【反义词】:"
						+ animal.getAntonym() + "\n【来源】:"
						+ animal.getDerivation() + "\n【示例】:"
						+ animal.getExamples();
				DialogUtil.showDialog(result,StudyAnimalActivity.this);
			}
		});</strong>
	}

	private void initAnimals() {
		animalDao = AnimalDao.getInstance(this);
		animalList = animalDao.getAllAnimals();
	}
}</span>

在util包下新建DialogUtil类,代码如下:

<span style="font-size:14px;">public class DialogUtil {
	public static void showDialog(String result,Context context){
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		LayoutInflater layoutInflater = LayoutInflater.from(context);
		View view = layoutInflater.inflate(R.layout.dialog_info, null);
		builder.setView(view);
		TextView tvIdiomInfo = (TextView) view.findViewById(R.id.tvIdiomInfo);
		tvIdiomInfo.setText(result);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
}</span>

修改AnimalAdapter类,加入两句代码:

<span style="font-size:14px;">viewHolder.btnSave.setFocusable(false);
viewHolder.btnSave.setFocusableInTouchMode(false);</span>

运行结果如图:


接下来进行做后一步,修改图标,代码如下:

<span style="font-size:14px;">android :icon="@drawable/logo"</span>


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值