乐学成语案例

一、

1创建数据库和表

      <1>需在项目下创建几个包,如图所示:

<2>数据库

首先使用Navicat Premium可视化界面来创建数据库 如图所示:


然后将所需要的表导入

2.将数据库文件拷贝到手机里存放数据库的位置

首先在res目录下这是因为raw目录,将idioms.db数据库复制到此目录下。这是因为raw目录的东西,会原封不动的拷到项目中去,不会转化为二进制文件

在db包下新建一个DBOpenHelper类代码如下:

/*实现将数据库文件从raw目录拷贝到手机里存放数据库的位置*/
public class DBOpenHelper {
	private final int BUFFER_SIZE=400000;//缓冲区大小
	public static final String DB_NAME="idioms.db";//保存的数据库文件名
	public static final String PACKAGE_NAME="cn.edu.bztc.happyidion.activity";//应用的包名
	public static final String DB_PATH="/data"+Environment.getDataDirectory().getAbsolutePath()+"/"+PACKAGE_NAME+"/databases";//在手机里存放数据库的位置
	private Context context;
	public DBOpenHelper(Context context){
		this.context=context;
	}
	public SQLiteDatabase openDatabase(){
		try {
			File myDataPath=new File(DB_PATH);
			if(!myDataPath.exists()){
				myDataPath.mkdirs();//如果没有这个目录则创建
			}
			String dbfile=myDataPath+"/"+DB_NAME;
			if(!(new File(dbfile).exists())){//判断数据库文件是否存在,如果不存在则执行导入,否则直接打开数据库
				InputStream is=context.getResources().openRawResource(R.raw.idioms);
				FileOutputStream fos=new FileOutputStream(dbfile);
				byte[] buffer=new byte[BUFFER_SIZE];
				int count=0;
				while((count=is.read(buffer))>0){
					fos.write(buffer,0,count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(dbfile,null);
			return db;
		} catch (FileNotFoundException e) {
			Log.e("MainActivity","File not found");
			e.printStackTrace();
		}catch (IOException e) {
			Log.e("MainActivity","IO exception");
			e.printStackTrace();
		}
		return null;
	}
}
然后就是搭建单元测试的环境,修改后的AndroidManifest文件如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.edu.bztc.happyidion.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="android.test.runner"/>
         </application>
         <instrumentation 
	    android:name="android.test.InstrumentationTestRunner"
	    android:targetPackage="cn.edu.bztc.happyidion.activity">
	</instrumentation>
	</manifest>
只要加入上述环境,单元测试环境就搭建起来了

接下来在test包下,新建DBOpenHelperTest继承AndroidTestCase,代码如下:

public class DBOpenHelperTest extends AndroidTestCase{
	public void testDBCopy(){
		DBOpenHelper dbOpenHelper=new DBOpenHelper(getContext());
		dbOpenHelper.openDatabase();
	}
}
    右击DBOpenHelperTest文件,选择Run as测试,若出现绿条,说明测试成功,若出现红条,说明代码错误,如图所示


接下来检验数据库有没有复制成功,切换到DDMS


3、创建实体类,在entity包下新建一个Aniaml类

public class Animal {
	private int id;
	private String name;//成语名称
	private String pronounce;//成语发音
	private String explain;//成语解释
	private String antonym;//反义词
	private String homoionym;//同义词
	private String derivation;//源自
	private String examples;//例子
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPronounce() {
		return pronounce;
	}
	public void setPronounce(String pronounce) {
		this.pronounce = pronounce;
	}
	public String getExplain() {
		return explain;
	}
	public void setExplain(String explain) {
		this.explain = explain;
	}
	public String getAntonym() {
		return antonym;
	}
	public void setAntonym(String antonym) {
		this.antonym = antonym;
	}
	public String getHomoionym() {
		return homoionym;
	}
	public void setHomoionym(String homoionym) {
		this.homoionym = homoionym;
	}
	public String getDerivation() {
		return derivation;
	}
	public void setDerivation(String derivation) {
		this.derivation = derivation;
	}
	public String getExamples() {
		return examples;
	}
	public void setExamples(String examples) {
		this.examples = examples;
	}
	
}
4、创建一个AniamlDao类,会把一些常用的数据库操作 封装起来,代码如下:

public class AnimalDao {
	private static AnimalDao animaiDao;
	private SQLiteDatabase db;
	/*将构造方法私有化*/
	private AnimalDao(Context context){
		DBOpenHelper dbHelper=new DBOpenHelper(context);
		db=dbHelper.openDatabase();
	}
	/*获取AnimalDao的实例*/
	public synchronized static AnimalDao getInstance(Context context){
		if(animaiDao==null){
			animaiDao=new AnimalDao(context);
		}
		return animaiDao;
	}
	/*从数据库读取所有的动物类成语*/
	public List<Animal> getAllAnimals(){
		List<Animal> list=new ArrayList<Animal>();
		Cursor cursor=db.query("animal",null,null,null,null,null,null);
		if(cursor.moveToNext()){
			do{
				Animal animal=new Animal();
				animal.setId(cursor.getInt(cursor.getColumnIndex("_id")));
				animal.setName(cursor.getString(cursor.getColumnIndex("name")));
				animal.setPronounce(cursor.getString(cursor.getColumnIndex("pronounce")));
				animal.setAntonym(cursor.getString(cursor.getColumnIndex("antonym")));
				animal.setHomoionym(cursor.getString(cursor.getColumnIndex("homoionym")));
				animal.setDerivation(cursor.getString(cursor.getColumnIndex("derivation")));
				animal.setExamples(cursor.getString(cursor.getColumnIndex("examples")));
				animal.setExplain(cursor.getString(cursor.getColumnIndex("explain")));
				list.add(animal);
			}while(cursor.moveToNext());
		}
		return list;
	}
}
接下来在AniamlDao测试是否获得所有动物类 成语

编写单元测试类,代码如下:

public class AnimalDaoTest extends AndroidTestCase{
	public void testGetAllAnimals(){
		AnimalDao animalDao=AnimalDao.getInstance(getContext());
		List<Animal> animals=animalDao.getAllAnimals();
		System.out.println(animals.size());
		for(Animal animal:animals){
			System.out.println(animal.getName());
		}
	}
}
结果如图所示:

二、显示主界面
在res/layout目录中新建activity_main.xml布局,代码如下所示:

<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"
    tools:context=".MainActivity" >

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <LinearLayout
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tab3"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>

</RelativeLayout>
然后在res的values目录的string.xml文件中定义所需要的字符串,代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">happyidiom</string>
    <string name="action_settings">Settings</string>

    <string name="title_study">学习</string>
    <string name="title_search">搜搜</string>
    <string name="title_game">游戏</string>
    <string name="title_save">收藏</string>
    <string name="title_help">帮助</string>
    <string name="animal">动物类</string>
</resources>
接下来要在activity包下新建MainActivity继承自Activity,代码如下所示:

public class MainActivity extends TabActivity{

	private TabHost tabHost;//导航栏控件
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//取消标题栏
        setContentView(R.layout.activity_main);
        tabHost=getTabHost();     //获取TabHost组件
      
        addTab("study",R.string.title_study,R.drawable.study,R.id.tab1);
        addTab("search",R.string.title_search,R.drawable.search,R.id.tab2<span style="font-family: Arial, Helvetica, sans-serif;">);</span>
        addTab("game",R.string.title_game,R.drawable.game,R.id.tab3);
        addTab("save",R.string.title_save,R.drawable.save,R.id.tab1);
        addTab("help",R.string.title_help,R.drawable.help,R.id.tab2);
    }
    /*定义每个Tab的显示内容*/
    private void addTab(String tag,int title_introduction,int title_icon,int content){
    	tabHost.addTab(tabHost.newTabSpec(tag).setIndicator(getString(title_introduction),getResources().getDrawable(title_icon)).setContent(content));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main, menu);
    	return true;
    }
}
在运行之前要配置AndroidManifest.xml文件,修改其代码如下所示:

<activity
            android:name="cn.edu.bztc.happyidion.activity.MainActivity"
            android:theme="@android:style/Theme.NoTitleBar"//将文字标题设置为空字符串
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
主要是注册了MainActivity,通过加入<intent-filter>将其设置为首先启动的类
  如果想让指示器显示在底部,只需要对activity_main.xml文件稍加修改,加入
<TabWidget 
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                >
                
            </TabWidget>
三、显示学习列表

首先需要准备好一组图片,分别对应每一种类别,让这些类别名称旁边都有一个图样,准备好文字资源,修改values 中的strings.xml文件如下:

<string-array name="category">
        <item>动物类</item>
        <item>自然类</item>
        <item>人物类</item>
        <item>季节类</item>
        <item>数字类</item>
        <item>寓言类</item>
        <item>其它类</item>
    </string-array>
然后定义一个实体类,作为ListView适配器的适配类型。
在entity包下建立Category,代码如下所示:

public class Category {
	private String name;//种类名字
	private int imageId;//图片资源id
	public Category(String name, int imageId) {
		super();
		this.name = name;
		this.imageId = imageId;
	}
	public String getName() {
		return name;
	}
	public int getImageId() {
		return imageId;
	}
}
在layout下新建activity_study.xml文件,主要添加了一个 ListView控件, 代码如下:

<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:listSelector="#00000000"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

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

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="horizontal" 
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    //用于显示类别的图片
    <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="@string/animal"
        android:gravity="center"
        android:textColor="#000000"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
接下来在应用包下创建adapter包,在该包下创建一个自定义的适配器,继承自ArrayAdapter,并将泛型指定为Category类,代码如下所示:

public class CategoryAdapter extends ArrayAdapter<Category>{

	private int resourceId;
	public CategoryAdapter(Context context, int resource,
			List<Category> categoryList) {
		super(context,resource, categoryList);
		resourceId=resource;
	}
	public View getView(int position, android.view.View convertView, android.view.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.categoryName=(TextView)view.findViewById(R.id.category_name);
			view.setTag(viewHolder);	
		}else{
			view=convertView;
			viewHolder=(ViewHolder) view.getTag();
		}
		viewHolder.categoryImage.setImageResource(category.getImageId());
		viewHolder.categoryName.setText(category.getName());
		return view;
	}
	class ViewHolder{
		ImageView categoryImage;
		TextView categoryName;
	}
}
下面在activity包下新建StudyActivity继承自Activity,代码如下所示:

import java.util.ArrayList;
import java.util.List;


import cn.edu.bztc.happyidiom.adapter.CategoryAdapter;
import cn.edu.bztc.happyidiom.entity.Category;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

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);//绑定适配器
		
	}

	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.main,menu);
		return true;
	}
}
修改AndroidManifest.xml文件将StudyActivity变为入口类,效果如图所示:


使ListView中的每一项都能被点击,需修改StudyActivity中的代码,如下所示:

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() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long id) {
				Category category=category.get(position);
                               Toast.makeText(StudyActivity.this,category.getName(),
                                Toast.LENGH_LONG).show();
	  		}
		});
	}

	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.main,menu);
		return true;
	}
}
为界面载入加入动画效果,

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

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromAlpha="0.0"
    android:toAlpha="1.0">
</alpha>

创建anim_layout_listview.xml文件,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@anim/anim_listview"
    android:animationOrder="random"
    android:delay="0.2">
</layoutAnimation>
最后修改activity_ study.xml布局文件,代码如下:

<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:listSelector="#00000000"
        android:layoutAnimation="@anim/anim_layout_listview"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>
修改MainActivity,将其与StudyActivity连起来,代码如下:

public class MainActivity extends TabActivity{

	private TabHost tabHost;//导航栏控件
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//取消标题栏
        setContentView(R.layout.activity_main);
        tabHost=getTabHost();     //获取TabHost实例
        /*一个Tab对应一个name名称,一个标题,一个图标,yigeActivity页面*/
        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.help,StudyActivity.class);
    }
    /*定义每个Tab的显示内容*/
    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)));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main, menu);
    	return true;
    }
}
通过intent,将选项卡和对应的StudyActivity关联起来了,效果如下图所示:


四、显示所有动物类成语的列表

 在layout下新建activity_aniaml.xml文件,主要添加了一个ListView控件,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<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>
然后需要为ListView的子项指定一个我们自定义的布局,在layout目录下新建animal_item.xml文件,代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<!-- 成语列表布局 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:padding="10dp" >
    <!-- android:descendantFocusability="blocksDescendants"使ListView中的子控件ImageButton失去焦点 -->
    <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:textColor="#000000"
        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>
接下来需要在应用的包下的adapter包创建自定义的适配器,这个适配器继承自ArrayAdapter,并将泛型指定为Aniaml类,新建类AniamlAdapter,代码如下所示:

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;
	}
}
接下来修改StudyActivity中的点击事件

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() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long id) {
				switch (position) {//position为0代表动物类
				case 0:
					Intent intent=new Intent(StudyActivity.this,StudyAnimalActivity.class);
					startActivity(intent);
					break;
				default:
					break;
				}
			}
		});
	}

	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.main,menu);
		return true;
	}
}
修改StudyActivity为入口类,运行效果如图所示:

此时点击收藏按钮没有任何反应,下面处理点击事件,修改AnimalAdapter类,加入事件处理,代码如下:

public class AnimalAdapter extends ArrayAdapter<Animal>{

	private int resourceId;
	private Context context;
	public AnimalAdapter(Context context, int resource,List<Animal> objects) {
		super(context,resource, objects);
		this.context=context;
		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);
			viewHolder.btnSave.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Toast.makeText(context,"你要收藏"+animal.getName()+"吗",Toast.LENGTH_SHORT).show();
				}
			});
			view.setTag(viewHolder);
		}else{
			view=convertView;
			viewHolder=(ViewHolder) view.getTag();
		}
		viewHolder.tvName.setText(animal.getName());//显示成语
		return view;
	}
	class ViewHolder{
		TextView tvName;
		ImageButton btnSave;
	}
}
运行效果如图所示:



五、显示每条成语的详细信息

首先在layout下新建布局dialog_info.xml,代码如下所示:

<!-- 对话框布局 -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:baselineAligned="@drawable/bg_ling"
        android:orientation="vertical">
        <TextView 
            android:id="@+id/tvIdiomInfo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
    </LinearLayout>
</ScrollView>
最外层是ScorollView组件,当内容较多时会出现垂直滚动条。

接下来需要修改StudyAnimalActivity,增加点击事件处理,代码如下所示:

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);
		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);
			}
		});
	}
	/*获取成语数据*/
	private void initAnimals() {
		animalDao=AnimalDao.getInstance(this);
		animalList=animalDao.getAllAnimals();
	}
}
这里DialogUtil.showDialog()方法是自定义的方法。在util包下新建DialogUtil类,代码如下所示:

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 tvdiomInfo=(TextView)view.findViewById(R.id.tvIdiomInfo);
		tvdiomInfo.setText(result);//设置之前定义的提示语句
		builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();//对话框关闭
			}
		});
		builder.create().show();//打开对话框
	}
}
效果如图所示:


六、修改图标和名称

将图片命名成logo.png,放入res/drawble-hdpi目录,修改AndroidManifest.xml文件代码,如下所示:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.edu.bztc.happyidion.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
     </application>  ......   </manifest>   















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值