乐学成语项目的实现

  首先给软件取名为HappyIdiom,在开始编码之前,需要先对程序进行需求分析,想一想HappyIdiom中应该具备哪些功能。将这些功能全部整理出来之后,我们才好动手一一实现。这里我认为HappyIdiom中至少应该具备以下功能:

1.成语分类学习:你可以根据自己喜欢的分类(动物类、人物类、季节类、自然类、数字类、语言类、其他类)来进行学习。

2.乐猜成语:学习之余玩玩猜成语游戏,寓教于乐。

3.成语收藏:当用户遇到自己想要保存的成语,点击保存按钮,即保存到收藏页面以方便用户再次查看,对已经掌握的成语,用户可以从收藏夹中删除。

4.成语查询:支持首字母查询,如一心一意可输入:yxyy。

  虽然看上去只有四个主要的功能点,但如果想要全部实现这些功能却用到UI/网络、数据存储等技术,因此还是非常考验综合能力的。

  分析完了需求之后,接下来就要进行技术的可行性分析了。首先要考虑的一个问题就是,我们如何才能得到所有的成语数据,以及如何才能获取每个成语的读音,解释,近义词反义词等信息。聚合网给我们提供了免费的聚合数据,网址如下:https://www.juhe.cn/docs/api/id/157  也可以从网上查找。

获取了数据库版本之后,就开始创建HappyIdiom这个项目了,在Eclipse中新建一个Android项目,项目名叫做HappyIdiom,包名叫做cn.edu.bztc.HappyIdiom,使用的是4.2的API,如图所示:

创建好了之后,然后再创建几个包,如图所示:

在res目录下新建raw目录,将idioms.db数据库复制到此目录下。这是因为raw目录的东西,android会原封不动的拷贝到程序中,而不会转换为二进制文件。在db包下新建一个DBOpenHelper类,代码如下:

package cn.edu.bztc.happyidiom.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import cn.edu.bztc.happyidiom.R;

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.happyidiom";
	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("Database", "File not found");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("Dtaabase", "IO exception");
			e.printStackTrace();
		}
		return null;

	}
}

上面的代码功能主要是使用输出流将idioms.db复制到手机中默认存放数据库的位置。

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

package cn.edu.bztc.happyidiom.test;

import cn.edu.bztc.happyidiom.db.DBOpenHelper;
import android.test.AndroidTestCase;

public class DBOpenHelperTest extends AndroidTestCase {
	public void testDBCopy() {
		DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext());
		dbOpenHelper.openDatabase();
	}
}

然后在entity包下新建一个Animal类,代码如下:

package cn.edu.bztc.happyidiom.entity;

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;
	}

}


可以看到,实体类的内容非常简单,基本就是生成数据库对应字段的get和set方法就可以了。接下来需要创建一个AnimalDao类,这个类可以将会把一些常用的数据库操作封装起来,以方便我们后面使用,代码如下所示:

package cn.edu.bztc.happyidiom.dao;

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

import cn.edu.bztc.happyidiom.db.DBOpenHelper;
import cn.edu.bztc.happyidiom.entity.Animal;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class AnimalDao {
	private static AnimalDao animalDao;
	private SQLiteDatabase db;

	private AnimalDao(Context context) {
		DBOpenHelper dbHelper = new DBOpenHelper(context);
		db = dbHelper.openDatabase();
	}

	public synchronized static AnimalDao getInstance(Context context) {
		if (animalDao == null) {
			animalDao = new AnimalDao(context);
		}
		return animalDao;

	}

	public List<Animal> getAllAnimals() {
		List<Animal> list = new ArrayList<Animal>();
		Cursor cursor = db.query("animal", null, null, null, null, null, null);
		if (cursor.moveToFirst()) {
			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("antonym")));
				animal.setDerivation(cursor.getString(cursor
						.getColumnIndex("derivation")));
				animal.setExamples(cursor.getString(cursor
						.getColumnIndex("examples")));
				list.add(animal);
			} while (cursor.moveToNext());

		}

		return list;

	}

}


可以看到,AnimalDao是一个单例类,我们将它的构造方法私有化,并提供了一个getInstance()方法来获取AnimalDao的实例,这样就可以保证全局范围内只会有一个AnimalDao的实例。接下来我们在AnimalDao中提供了一个方法getAllAnimals()该方法用来获取所有的动物类成语。编写单元测试类AnimalDaoTest继承AndroidTestCase,代码如下:

package cn.edu.bztc.happyidiom.test;

import java.util.List;

import cn.edu.bztc.happyidiom.dao.AnimalDao;
import cn.edu.bztc.happyidiom.entity.Animal;
import android.test.AndroidTestCase;

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的drawable-hdpi目录考入需要的图片素材,在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" >
            </TabWidget>

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

                <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>

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

</RelativeLayout>



布局文件中的内容比较简单,主要是拖了一个TabHost空间到界面上

然后再res的values目录的strings.xml文件中定义所需的字符串。代码如下:

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

    <string name="app_name">HappyIdiom</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_main">MainActivity</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-array name="category">
        <item>动物类</item>
        <item>自然类</item>
        <item>人物类</item>
        <item>季节类</item>
        <item>数字类</item>
        <item>寓言类</item>
        <item>其他类</item>
    </string-array>

</resources>


接下来也是最关键的一步,在activity包下新建MianActivity继承自Activity,代码如下所示:

package cn.edu.bztc.happyidiom.avtivity;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.widget.TabHost;
import cn.edu.bztc.happyidiom.R;

public class MainActivity extends TabActivity {
	private TabHost tabHost;

	protected void onCreate(Bundle savedInstanceState) {
		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;

	}

}


然后定义一个实体类,作为ListView适配器的适配类型。在entity包下新建Category,代码如下所示:

package cn.edu.bztc.happyidiom.entity;

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;
	}
	
	

}


Category类中只有两个字段,name表示类的名字,imageId表示类别对应图片的资源id。

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

<?xml version="1.0" encoding="utf-8"?>
<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"
        android:layoutAnimation="@anim/anim_layout_listview"
        android:listSelector="#00000000" >
    </ListView>

</RelativeLayout>


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

<?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:orientation="horizontal"
    android:padding="10dp" >

    <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:gravity="center"
        android:text="@array/category"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>


在这个布局中,我们定义了一个ImageView用于显示类别图片,又定义了一个TextView用于显示类别的名称。接下来需要在应用包下创建adapter包,再改包下创建一个自定义的适配器,这个适配器继承自ArrayAdapter,并将泛型指定为Category类,新建类CategoryAdapter,代码如下所示:

package cn.edu.bztc.happyidiom.adapter;

import java.util.List;

import cn.edu.bztc.happyidiom.R;
import cn.edu.bztc.happyidiom.entity.Category;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CategoryAdapter extends ArrayAdapter<Category> {
	private int resourceId;

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

	}

	public View getView(int position, View convertView, ViewGroup parent) {
		Category category = getItem(position);
		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;

	}
}


CategoryAdapter重写了父类的一组构造函数,用于将上下文、ListView子项布局id和数据都传递进来。另外有重写了getView()方法,这个方法每个子项被滚动到屏幕内的时候调用。在getView方法中,首先通过getItem()方法得到当前项的Category实例,然后使用L ayouInflater来为这个字项加载我们传入的布局,接着调用View的findViewById()方法分别获取ImageView和TextView的实例,并分别调用它们的setImageResource()和SetText()方法来设置爱显示的图片和文字,最后将布局返回,这样我们自定义的适配器就完成了,下面在activity包下新建StudyActivity继承自Activity,代码如下所示:

package cn.edu.bztc.happyidiom.avtivity;

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

import cn.edu.bztc.happyidiom.*;
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.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;

	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<?> adapterView, 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<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]));
		}

	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.study, menu);
		return true;
	}

}


可以看到,这里添加了一个initCategories()方法,用于初始化类别数据。接着我们在onCreate()方法中创建了一个CategoryAdapter对象,并将CategoryAdapter作为适配器传递给了List。这样定制的ListView界面任务就完成了。

修改清单文件AndroidManifest.xml,代码如下所示:

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="android.test.runner" />

        <activity
            android:name="cn.edu.bztc.happyidiom.avtivity.MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@android:style/Theme.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="cn.edu.bztc.happyidiom.avtivity.StudyActivity" >
        </activity>
        <activity android:name="cn.edu.bztc.happyidiom.avtivity.StudyAnimalActivity" >
        </activity>
    </application>

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="cn.edu.bztc.happyidiom" >
    </instrumentation>

</manifest>


这时界面载入的过程有些生硬,下面为界面增加淡入淡出的动画效果,在res目录下新建anim目录,在下面创建anim_listview.xml文件,代码如下:

<?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>


设置了一个Alpa动画,从无到有的过程,创建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>


在layout下新建activity_animal.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: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:layout_alignParentRight="true"
        android:layout_alignTop="@+id/tvName"
        android:background="@null"
        android:src="@drawable/btnsave" />

</RelativeLayout>


接下来需要在应用包下创建adapter包,再改包下创建一个自定义的适配器,这个适配器继承自ArrayAdapter,并将泛型指定为Animal类,新建类AnimalAdapter,代码如下所示:

package cn.edu.bztc.happyidiom.adapter;

import java.util.List;
import cn.edu.bztc.happyidiom.R;
import cn.edu.bztc.happyidiom.entity.Animal;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

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;

	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final Animal animal = getItem(position);

		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);
			viewHolder.btnSave.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					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;

	}

}


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

package cn.edu.bztc.happyidiom.avtivity;

import java.util.List;

import cn.edu.bztc.happyidiom.R;
import cn.edu.bztc.happyidiom.adapter.AnimalAdapter;
import cn.edu.bztc.happyidiom.dao.AnimalDao;
import cn.edu.bztc.happyidiom.entity.Animal;
import cn.edu.bztc.happyidiom.util.DialogUtil;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class StudyAnimalActivity extends Activity {
	private List<Animal> animalList;
	private AnimalDao animalDao;
	private ListView lvAnimalList;

	protected void onCreate(Bundle savedstInanceState) {
		super.onCreate(savedstInanceState);
		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() {
			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.getExamples() + "\n【示例】:"
						+ animal.getExamples();
				DialogUtil.showDialog(result, StudyAnimalActivity.this);
			}
		});

	}

	private void initAnimals() {
		animalDao = AnimalDao.getInstance(this);
		animalList = animalDao.getAllAnimals();

	}

}



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

<?xml version="1.0" encoding="utf-8"?>
<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:background="@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>


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

package cn.edu.bztc.happyidiom.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import cn.edu.bztc.happyidiom.R;

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) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

}



最后运行一下程序:


 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值