Android基礎知識【項目實訓】【5】

來源:互聯網
上載者:User

標籤:android

【該項目實訓是Android基礎知識的一個綜合練習,特別提示:項目中會用到一些圖片素材,都是隨意整理的,稍後會上傳一個資源,包含該事項項目的準系統,也含有圖片素材】

【項目題目】:校園訂餐App設計綜合案例【目標】

主介面中包含兩個二級子介面,分別是活動介面和賬單介面,下面介紹它們的實現代碼和布局檔案。

1、下面這個是 活動介面的Activity代碼,因為這個介面載入時需要 讀取資料庫中資料了,所有功能的實現上會涉及到 db那個包中一些類。

注意這個Activity也是繼承 ActivityGroup的

public class DiscountFoodActivity extends ActivityGroup implements OnItemClickListener {TabHost innerTab;ListView promotionFoodList,discountFoodList;//促銷列表資料,List<FoodInfo> pdata;//折扣列表資料List<FoodInfo> ddata;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_discount_food);promotionFoodList=(ListView) findViewById(R.id.promotionFoodList);discountFoodList=(ListView) findViewById(R.id.discountFoodList);innerTab=(TabHost) findViewById(R.id.innerTab_discount);//初始化的內部TabinitInnerTabHost();initListView();//初始化列表資料//添加監聽器,監聽清單項目的點擊promotionFoodList.setOnItemClickListener(this);discountFoodList.setOnItemClickListener(this);}//初始化活動食品列表 和 折扣食品列表private void initListView() {//擷取資料庫EatDbHelper dbh=new EatDbHelper(this,"fooddb.db3",null,1);SQLiteDatabase db =dbh.getReadableDatabase(); pdata =new FoodDao().queryFood(db, "ispromotion=?", new String[]{"1"}, "price DESC");FoodListAdapter fla =new FoodListAdapter(this,pdata,R.layout.foodlist_item); promotionFoodList.setAdapter(fla);ddata =new FoodDao().queryFood(db, "discount<?", new String[]{"1"}, "price DESC");fla =new FoodListAdapter(this,ddata,R.layout.foodlist_item); discountFoodList.setAdapter(fla);}private void initInnerTabHost() {innerTab.setup(getLocalActivityManager());TabSpec t1=innerTab.newTabSpec("inner_dis_t1");t1.setIndicator("今日活動", getResources().getDrawable(R.drawable.ic_launcher));t1.setContent(R.id.innerTab_discount_tab1);TabSpec t2=innerTab.newTabSpec("inner_dis_t2");t2.setIndicator("今日折扣", getResources().getDrawable(R.drawable.ic_launcher));t2.setContent(R.id.innerTab_discount_tab2);innerTab.addTab(t1);innerTab.addTab(t2);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.discount_food, menu);return true;}@Overridepublic void onItemClick(AdapterView<?> lv, View view, int index, long arg3) {Intent intent =new Intent(this,FoodDetailActivity.class);Bundle bd =new Bundle();//Log.i("Msg", "當前點擊列表"+lv + "  "+lv.getId());if(lv.getId()==R.id.promotionFoodList){bd.putSerializable("food",pdata.get(index));//Log.i("Msg", "當前選擇:"+pdata.get(index).getFoodName());}else if(lv.getId()==R.id.discountFoodList){bd.putSerializable("food",ddata.get(index));//Log.i("Msg", "當前選擇:"+ddata.get(index).getFoodName());}intent.putExtras(bd);startActivity(intent);}}
2、布局介面,項目中用到很多資源,現在把這些資源的結果 展示一下。


活動Activity使用的介面是activity_discount_food.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=".DiscountFoodActivity" >    <TabHost        android:id="@+id/innerTab_discount"        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" >                <LinearLayout                    android:id="@+id/innerTab_discount_tab1"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:orientation="vertical"                     >                     <ListView                         android:id="@+id/promotionFoodList"                         android:layout_width="match_parent"                         android:layout_height="match_parent"                         >                     </ListView>                </LinearLayout>                <LinearLayout                    android:id="@+id/innerTab_discount_tab2"                    android:layout_width="match_parent"                    android:orientation="vertical"                    android:layout_height="match_parent" >                    <ListView                         android:id="@+id/discountFoodList"                         android:layout_width="match_parent"                         android:layout_height="match_parent"                         >                     </ListView>                </LinearLayout>            </FrameLayout>        </LinearLayout>    </TabHost></RelativeLayout>
其實這也是一個tab導航,只是它的標籤導航在上面。
3、因為要讀取活動和折扣 食物資料,因此準備了兩個集合
//促銷列表資料,List<FoodInfo> pdata;//折扣列表資料List<FoodInfo> ddata;

這裡的FoodInf是一個實體類,請留意對屬性的注釋。

package com.example.entity;import java.io.Serializable;import android.graphics.Bitmap;public class FoodInfo implements Serializable {private String _id,foodName;private String price;private String isPromotion;//菜品是否促銷活動 1 有活動, 0 沒有活動private String discount="1";//折扣private String category;//食物所屬類別,主食、配菜、飲料,其他四類private String type;//菜系,酸甜苦辣鹹等,魯粵川蘇等private String score;//菜品累計得分private int shopId;//餐館IDprivate ShopInfo shop;//食物所屬餐館private Bitmap img;private String imgId;private String description;//關於食物的描述public String getFoodName() {return foodName;}public void setFoodName(String foodName) {this.foodName = foodName;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}public String getCategory() {return category;}public void setCategory(String category) {this.category = category;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getScore() {return score;}public void setScore(String score) {this.score = score;}public ShopInfo getShop() {return shop;}public void setShop(ShopInfo shop) {this.shop = shop;}public String get_id() {return _id;}public void set_id(String _id) {this._id = _id;}public int getShopId() {return shopId;}public void setShopId(int shopId) {this.shopId = shopId;}public String getIsPromotion() {return isPromotion;}public void setIsPromotion(String isPromotion) {this.isPromotion = isPromotion;}public String getDiscount() {return discount;}public void setDiscount(String discount) {this.discount = discount;}public Bitmap getImg() {return img;}public void setImg(Bitmap img) {this.img = img;}public String getImgId() {return imgId;}public void setImgId(String imgId) {this.imgId = imgId;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}@Overridepublic String toString() {return "FoodInfo [_id=" + _id + ", foodName=" + foodName + ", price="+ price + ", isPromotion=" + isPromotion + ", discount="+ discount + ", category=" + category + ", type=" + type+ ", score=" + score + ", shopId=" + shopId + ", shop=" + shop+ ", img=" + img + ", imgId=" + imgId + "]";}}

4、上面的倆集合中的資料是靠 db中的類給填充的。

pdata =new FoodDao().queryFood(db, "ispromotion=?", new String[]{"1"}, "price DESC");
FoodDao就是一個專門讀取 食物資料的類,其代碼如下:

public class FoodDao {public List<FoodInfo> queryFood(SQLiteDatabase db,String sel,String []selArg,String order){List<FoodInfo> fs=new ArrayList<FoodInfo>();Cursor c=db.query("tb_foodInfo",new String[]{"_id","foodName","category","type","price","score","imgId","shopId","discount","isPromotion"}, sel,selArg,null,null,order);Log.i("Msg", "讀取記錄條數 :"+c.getCount());c.moveToFirst();while(!c.isAfterLast()){FoodInfo f =new FoodInfo();f.set_id(c.getString(0));f.setFoodName(c.getString(1));f.setCategory(c.getString(2));f.setType(c.getString(3));f.setPrice(c.getString(4));f.setScore(c.getString(5));String imgId=c.getString(6);f.setImgId(Integer.parseInt(imgId.substring(2),16)+"");f.setShopId(c.getInt(7));f.setDiscount(c.getString(8));f.setIsPromotion(c.getString(9));//Log.i("Msg", f.toString());fs.add(f);c.moveToNext();}c.close();return fs;}}
5、讀取完資料了,就可以採用適配器 把資料繫結到 列表上了。

FoodListAdapter fla =new FoodListAdapter(
this,pdata,R.layout.foodlist_item); 

FoodListAdapter是一個繼承了BaseAdapter的適配器。(   容易理解期間,這個適配器寫的並不通用,但應該容易理解了)

代碼如下:

public class FoodListAdapter extends BaseAdapter {private Context context;private List<FoodInfo> data;private int layout;public FoodListAdapter(Context context, List<FoodInfo> data, int layout) {super();this.context = context;this.data = data;this.layout = layout;}@Overridepublic int getCount() {return data.size();}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn data.get(arg0);}@Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn arg0;}@Overridepublic View getView(int index, View arg1, ViewGroup arg2) {LayoutInflater inflater =LayoutInflater.from(context);View v =inflater.inflate(layout, null);ImageView iv =(ImageView) v.findViewById(R.id.foodlist_item_img);iv.setImageResource(Integer.parseInt(data.get(index).getImgId()));TextView name=(TextView) v.findViewById(R.id.foodlist_item_name);name.setText(data.get(index).getFoodName());TextView category=(TextView) v.findViewById(R.id.foodlist_item_category);category.setText(data.get(index).getCategory());TextView type=(TextView) v.findViewById(R.id.foodlist_item_type);type.setText(data.get(index).getType());TextView price=(TextView) v.findViewById(R.id.foodlist_item_price);price.setText("¥"+data.get(index).getPrice());float zk =Float.parseFloat(data.get(index).getDiscount());if(zk<1){TextView discount=(TextView) v.findViewById(R.id.foodlist_item_discount);discount.setText("折扣:"+(zk*10)+"折");}TextView score=(TextView) v.findViewById(R.id.foodlist_item_score);score.setText("百米分:"+data.get(index).getScore()+"米");return v;}}

6、其中 列表
ListView promotionFoodList,discountFoodList;
它們的清單項目布局是一樣的,統一採用布局檔案:

<pre name="code" class="html"><?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" >    <ImageView        android:id="@+id/foodlist_item_img"        android:layout_width="60dp"        android:layout_height="60dp"        android:background="@drawable/imgbg"        android:src="@drawable/food_02" />    <TextView        android:id="@+id/foodlist_item_name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toRightOf="@id/foodlist_item_img"        android:layout_marginLeft="8dp"        android:text="菜品"        android:textAppearance="?android:attr/textAppearanceLarge" />    <TextView        android:id="@+id/foodlist_item_category"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toRightOf="@id/foodlist_item_name"        android:layout_marginLeft="8dp"        android:text="中餐"        android:textAppearance="?android:attr/textAppearanceMedium" />    <TextView        android:id="@+id/foodlist_item_type"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toRightOf="@id/foodlist_item_category"        android:layout_marginLeft="8dp"        android:text="酸辣"        android:textAppearance="?android:attr/textAppearanceMedium" />    <TextView        android:id="@+id/foodlist_item_price"        android:layout_width="wrap_content"        android:layout_height="wrap_content"android:layout_below="@id/foodlist_item_name"android:layout_alignLeft="@id/foodlist_item_name"        android:layout_marginTop="8dp"        android:text="¥10.00"        android:textAppearance="?android:attr/textAppearanceSmall" />    <TextView        android:id="@+id/foodlist_item_discount"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toRightOf="@id/foodlist_item_price"        android:layout_alignBottom="@id/foodlist_item_price"        android:layout_marginLeft="8dp"        android:text=""        android:textAppearance="?android:attr/textAppearanceSmall" />    <TextView        android:id="@+id/foodlist_item_score"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toRightOf="@id/foodlist_item_discount"        android:layout_alignBottom="@id/foodlist_item_discount"android:layout_alignParentRight="true"android:layout_marginRight="8dp"android:gravity="right"                android:text="評分:122"        android:textAppearance="?android:attr/textAppearanceSmall" /></RelativeLayout>



折扣介面說完,下一篇說 賬單介面。

Android基礎知識【項目實訓】【5】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.