標籤頁(TabHost+TabWidget)的使用


標籤頁在顯示上是相當方便且用途廣泛的元件,在電話簿,訊息中常常可見,簡單的範例如下圖

















首先是 TabHost 和 TabWidget 的關係, TabHost 包含著 TabWidget , 可以有多個 TabWidget 的存在,如上圖就包含 4 個 TabWidget (消費清單,本日消費,本周消費,本月消費),每個 TabWidget 可以視為不同的 Activity ,當手指觸碰到不同的 TabWidget ,就會執行不同的 TabWidget, TabHost 的 xml 結構如下

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
   3:      android:id="@android:id/tabhost"
   4:      android:layout_width="fill_parent"
   5:      android:layout_height="fill_parent" >
   6:   
   7:      <LinearLayout
   8:          android:id="@+id/LinearLayout01"
   9:          android:layout_width="fill_parent"
  10:          android:layout_height="fill_parent"
  11:          android:orientation="vertical" >
  12:   
  13:          <TabWidget
  14:              android:id="@android:id/tabs"
  15:              android:layout_width="match_parent"
  16:              android:layout_height="wrap_content" />
  17:   
  18:          <FrameLayout
  19:              android:id="@android:id/tabcontent"
  20:              android:layout_width="fill_parent"
  21:              android:layout_height="fill_parent" />
  22:      </LinearLayout>
  23:   
  24:  </TabHost>


這是標準的 TabHost 的 xml 格式,第 7 行指出是個線性垂直的佈局,且依序為 TabWidget(標籤頁),以及其內容(FrameLayout),接著來看 TabHost的程式碼,如下

   1:  package com.example.helloworld;
   2:   
   3:  import android.app.TabActivity;
   4:  import android.content.Intent;
   5:  import android.os.Bundle;
   6:  import android.widget.TabHost;
   7:  import android.widget.TabHost.TabSpec;
   8:   
   9:  @SuppressWarnings("deprecation")
  10:  public class Table_Flow extends TabActivity{
  11:   
  12:      public void onCreate(Bundle savedInstanceState){
  13:          super.onCreate(savedInstanceState);
  14:          
  15:          setContentView(R.layout.table_host);
  16:          
  17:          initView();
  18:      }
  19:      
  20:      
  21:      void initView(){
  22:          
  23:          TabHost thost = getTabHost();// build tabhost
  24:          
  25:          Intent inte = new Intent();
  26:          inte.setClass(Table_Flow.this, Table_widget4.class);
  27:          TabSpec ts = thost.newTabSpec("tab4");
  28:          ts.setContent(inte);
  29:          ts.setIndicator("消費清單");
  30:          thost.addTab(ts);
  31:          
  32:          inte = new Intent();
  33:          inte.setClass(Table_Flow.this, Table_widget1.class);
  34:          TabSpec ts1 = thost.newTabSpec("tab1");
  35:          ts1.setContent(inte);
  36:          ts1.setIndicator("本日消費");        
  37:          thost.addTab(ts1);
  38:          
  39:          inte = new Intent();
  40:          inte.setClass(Table_Flow.this, Table_widget2.class);
  41:          TabSpec ts2 = thost.newTabSpec("tab2");
  42:          ts2.setContent(inte);
  43:          ts2.setIndicator("本周消費");
  44:          thost.addTab(ts2);
  45:          
  46:          inte = new Intent();
  47:          inte.setClass(Table_Flow.this, Table_widget2.class);
  48:          TabSpec ts3 = thost.newTabSpec("tab3");
  49:          ts3.setContent(inte);
  50:          ts3.setIndicator("本月消費");
  51:          thost.addTab(ts3);
  52:          
  53:          thost.setCurrentTab(0);
  54:      }
  55:  }
  56:   
  57:   
  58:   

注意第 10 行繼承 TabActivity , 第 15 行套用上述的 xml 佈局 ,接著就是對各個 TabWidget 的初始化(initView)
第 23 行取得 TabHost 物件 thost
第 25 ~ 30 行為建立第 1 個 TabWidget 的內容
第 26 行注意 Table_widget4.class 必須先建立好,這代表當點選該標籤頁就會執行的類別
第 27 行建立 TabSpec 物件, tab4 代表該標籤頁的 Tag,之後若有需要可取得 Tag 即可
第 28 行設定 Content 內容,其對應的類別為 Table_widget4.class
第 29 行顯示的內容
第 30 行加入TabSpec

接著選擇其中 1 個最簡單的 TabWidget 來看(Table_widget2.class),其內容為

   1:  package com.example.helloworld;
   2:   
   3:  import android.app.Activity;
   4:  import android.os.Bundle;
   5:   
   6:  public class Table_widget2 extends Activity{
   7:   
   8:      public void onCreate(Bundle savedInstanceState){
   9:          super.onCreate(savedInstanceState);
  10:          
  11:          
  12:      }
  13:  }


是的~ 這個就是最簡單的 TabWidget ,當然你可以任意改寫其內容來達到需求

顯示自訂的清單內容(ArrayList+SimpleAdapter+ListView)


在 "顯示簡單的清單內容" 中提到 String + ArrayAdapter + ListView 可達到簡單的清單顯示(單行單筆資訊),如下圖每行只有顯示1個字串(aaaaaa,bbbbbbb等等)


















那如果想達到單行多筆資訊顯示就必須使用 ArrayList + SimpleAdapter + ListView 才能達到需求,如下圖每行有 3 個資訊(2012/01/01 , 111111 , 這是備註1 )


















首先是 ArrayList ,它的作用如同上述範例中的 String 一樣,負責提供顯示的資訊(3個字串),在這裡還必須搭配 map 來使用, map 提供 key - value 的對應型態, 1個 key 對應 1個 value ,由於我們要加入 3 個資訊, map 也必須放入 3 個 key - value 的元素,如下

   1:  map.put("str1", "2012/01/01");
   2:  map.put("str2", "111111");
   3:  map.put("str3", "這是備註1");

接著把 map 加到 list 中

   1:  list.add(map);

這樣就完成 3 個資訊的顯示,接著為 SimpleAdapter 的使用,和 ArrayAdapter 一樣提供顯示資訊(ArrayList)與清單(ListView)的橋樑,如下

   1:          SimpleAdapter sa = new SimpleAdapter(
   2:                  this, 
   3:                  list, 
   4:                  R.layout.test2,
   5:                  new String[]{"str1","str2","str3"},
   6:                  new int[] { R.id.date, R.id.money , R.id.detail});

建立需要 5 個參數,第 1個參數為 Context ,傳入自己(this)即可,第 2 個參數為資訊內容,就是剛剛提到的 ArrayList , 第 3 個參數為顯示資訊的格式,必須在 xml 中定義, R.layout.test2 如下

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <!-- Copyright (C) 2006 The Android Open Source Project
   3:   
   4:       Licensed under the Apache License, Version 2.0 (the "License");
   5:       you may not use this file except in compliance with the License.
   6:       You may obtain a copy of the License at
   7:    
   8:            http://www.apache.org/licenses/LICENSE-2.0
   9:    
  10:       Unless required by applicable law or agreed to in writing, software
  11:       distributed under the License is distributed on an "AS IS" BASIS,
  12:       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13:       See the License for the specific language governing permissions and
  14:       limitations under the License.
  15:  -->
  16:  <TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android"
  17:      android:layout_width="match_parent"
  18:      android:layout_height="wrap_content"
  19:      android:minHeight="?android:attr/listPreferredItemHeightSmall"
  20:      android:mode="twoLine" >
  21:   
  22:      <TextView
  23:          android:id="@+id/date"
  24:          android:layout_width="wrap_content"
  25:          android:layout_height="wrap_content"
  26:          android:text="2012/01/01"
  27:          android:textAppearance="?android:attr/textAppearanceSmall" />
  28:   
  29:      <TextView
  30:          android:id="@+id/money"
  31:          android:layout_width="wrap_content"
  32:          android:layout_height="wrap_content"
  33:          android:layout_below="@+id/date"
  34:          android:layout_toRightOf="@+id/date"
  35:          android:text="-$99999"
  36:          android:maxEms="4"
  37:          android:singleLine="true"
  38:          android:textAppearance="?android:attr/textAppearanceListItem" />
  39:   
  40:      <TextView
  41:          android:id="@+id/detail"
  42:          android:layout_width="wrap_content"
  43:          android:layout_height="wrap_content"
  44:       
  45:          android:layout_below="@+id/date"
  46:          android:layout_toRightOf="@+id/date"
  47:          android:layout_marginLeft="120dp"
  48:          android:text="這是備註"
  49:          
  50:          android:maxLines="2"
  51:          android:ellipsize="end"
  52:          android:textAppearance="?android:attr/textAppearanceSmall" />
  53:   
  54:  </TwoLineListItem>

內容其實很簡單,就是 3 個 TextView 的定義也代表資訊的顯示格式,第 4 和 5 個參數代表對應的值,如 "str1" 就是對應 R.id.date(也就是顯示資訊的 2012/01/01 ), "str2" 對應 R.id.money(為顯示資訊的 111111 ) , "str3" 對應 R.id.detail(為顯示資訊的 這是備註1),如此完成 SimpleAdapter 的建立,最後是 ListView 的建立,只需要設定佈局中的格式,以及將剛剛建立的 SimpleAdapter 傳入即可,如下

   1:  lv = (ListView) findViewById(R.id.listview1);
   2:  lv.setAdapter(sa);

最後的程式碼如下

   1:   
   2:  public class Table_widget4 extends Activity{
   3:      
   4:      String[] strArr1 = {"2012/01/01","2012/01/02","2012/01/03","2012/01/04","2012/01/05"
   5:              ,"2012/01/01","2012/01/02","2012/01/03","2012/01/04","2012/01/05"
   6:              ,"2012/01/01","2012/01/02","2012/01/03","2012/01/04","2012/01/05"};
   7:      
   8:      String[] strArr2 = {"111111","222222","3333333","4444444","55555555555555555"
   9:              ,"111111","222222","3333333","4444444","55555555555555555"
  10:              ,"111111","222222","3333333","4444444","55555555555555555"};
  11:      
  12:      String[] strArr3 = {"這是備註1","這是備註222222222222222222222222","這是備註3","這是XXXOOO","這是備註"
  13:              ,"這是備註1","這是備註222222","這是備註3","這是XXXOOO","這是備註"
  14:              ,"這是備註1","這是備註222222","這是備註3","這是XXXOOO","這是備註"};
  15:      
  16:      ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
  17:      
  18:      ListView lv;
  19:      
  20:      public void onCreate(Bundle savedInstanceState){
  21:          super.onCreate(savedInstanceState);
  22:          
  23:          setContentView(R.layout.tabwidget4);
  24:          
  25:          initXml();
  26:          
  27:      }
  28:      
  29:      @SuppressLint("NewApi")
  30:      void initXml(){
  31:   
  32:          for(int i=0; i<strArr1.length; i++){
  33:              
  34:              HashMap<String, String> map = new HashMap<String, String>();
  35:              
  36:              map.put("str1", strArr1[i]);
  37:              map.put("str2", strArr2[i]);
  38:              map.put("str3", strArr3[i]);
  39:              
  40:              list.add(map);            
  41:          }
  42:          
  43:          
  44:          
  45:          SimpleAdapter sa = new SimpleAdapter(
  46:                  this, 
  47:                  list, 
  48:                  R.layout.test2,
  49:                  new String[]{"str1","str2","str3"},
  50:                  new int[] { R.id.date, R.id.money , R.id.detail});
  51:          
  52:          
  53:          
  54:          lv = (ListView) findViewById(R.id.listview1);
  55:          lv.setAdapter(sa);
  56:          
  57:          
  58:          
  59:      }
  60:      
  61:      
  62:  }


其中關於資訊的顯示有一些小技巧,如指定顯示單行,限制字數等等,都在 R.layout.test2 中













ListView 的清單起始動畫使用(LayoutAnimationController)


這也是從範例中挖出來的,使用 ListView 來顯示清單時,預設的顯示方式是瞬間顯示,沒有任何的動畫,你可以使用 anim + LayoutAnimationController ,讓你的清單顯示增加質感,使用方式相當簡單,當已經處理完 ListView 的建立後,再加上 anim 和 LayoutAnimationController 即可,如下

   1:      void listShowAnim(){
   2:          
   3:          AnimationSet set = new AnimationSet(true);
   4:   
   5:          Animation animation;
   6:          
   7:          animation = new TranslateAnimation(-300.0f,0.0f,0.0f,0.0f);
   8:          animation.setDuration(1000);
   9:          set.addAnimation(animation);
  10:          
  11:  //        Animation animation;
  12:  //        animation = new AlphaAnimation(0.0f, 1.0f);
  13:  //        animation.setDuration(500);
  14:  //        set.addAnimation(animation);
  15:  //
  16:  //        animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
  17:  //                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
  18:  //                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
  19:  //        animation.setDuration(100);
  20:  //        set.addAnimation(animation);
  21:   
  22:          //every sublist action move, 0.0f: action together
  23:          LayoutAnimationController controller = new LayoutAnimationController(
  24:                  set, 0.0f);
  25:   
  26:          lv.setLayoutAnimation(controller);
  27:          
  28:      }

第 1 行為動畫方法的名子,以我的範例而言,它放在 initXml() 之後呼叫
第 3 行建立 AnimationSet set 如果想使用多種動畫就使用 AnimationSet ,只有1種的話使用 Animation 即可
第 5 行到第 8 行就是第 1 個動畫的建立,單純的移位動作
第 9 行把動畫加入 set
第 11 ~ 22行的註解就是多種動畫的示範
第 23 行使用 LayoutAnimationController 可以決定 ListView 中的清單是否一起動作, 0.0f 代表一起動作,如果是 1.0f 的話代表清單會以 1 秒為單位依序動作
第 26 行執行動畫,該動畫為從左邊移位進入畫面置中位置

最後把它放到 initXml() 後呼叫

   1:  public void onCreate(Bundle savedInstanceState){
   2:          super.onCreate(savedInstanceState);
   3:          
   4:          setContentView(R.layout.tabwidget4);
   5:          
   6:          initXml();
   7:          
   8:          listShowAnim();
   9:      }


結果為


 清單移動中...


清單移動中...




顯示簡單的清單內容(string+ArrayAdapter+ListView)


想要顯示簡單的清單內容可以使用 ArrayAdapter + ListView 來達成, 把想要顯示的內容以及格式加到 ArrayAdapter 中,在設定到 ListView 就完成了,以下以步驟的方式來完成

1.在 setContentView 中 的佈局檔必須加入 ListView,

R.layout.tabwidget4

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   3:      android:layout_width="match_parent"
   4:      android:layout_height="match_parent" >
   5:   
   6:      <ListView
   7:          android:id="@+id/listview1"
   8:          android:layout_width="match_parent"
   9:          android:layout_height="wrap_content"
  10:          android:layout_alignParentLeft="true"
  11:          android:layout_alignParentTop="true" >
  12:      </ListView>
  13:      
  14:      <Button
  15:          android:id="@+id/buttonexit"
  16:          android:layout_width="wrap_content"
  17:          android:layout_height="wrap_content"
  18:          android:layout_alignParentBottom="true"
  19:          android:layout_alignParentRight="true"
  20:          android:text="@string/exit" 
  21:          android:shadowDx="20"
  22:          />
  23:   
  24:      <Button
  25:          android:id="@+id/buttonadd"
  26:          android:layout_width="wrap_content"
  27:          android:layout_height="wrap_content"
  28:          android:layout_alignParentBottom="true"
  29:          android:layout_alignParentLeft="true"
  30:          android:text="@string/add_record" />
  31:   
  32:      
  33:   
  34:  </RelativeLayout>

第 6 ~ 12行就是 ListView 的設定,接著將要顯示的內容和格式設定到 ArrayAdapter 中

   1:  //use arrAdapt
   2:  ArrayAdapter<String> arrAdapt = new ArrayAdapter<String>(this, R.layout.tabwidget4_textview, strArr);

第 2 行第 2 個參數就是顯示的格式,如下
R.layout.tabwidget4_textview





   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
   3:     
   4:      android:layout_width="match_parent"
   5:          android:layout_height="wrap_content"
   6:      android:layout_marginLeft="?android:attr/listPreferredItemPaddingLeft"
   7:      android:layout_marginTop="8dip"
   8:          android:textAppearance="?android:attr/textAppearanceListItem"
   9:          
  10:  />
  11:   
  12:      

內容只是簡單的 TextView 格式

第 3 個參數為顯示的內容

   1:  String[] strArr = {"aaaaaa","bbbbbbb","ccccccc","ddddddd","eeeeeee"};

最後建立 ListView 並設定 ArrayAdapter 即可

   1:  ListView lv1 = (ListView)findViewById(R.id.listview1);
   2:  lv1.setAdapter(arrAdapt);


結果就像這樣


















在單個清單中想要顯示多個資訊的話使用 ArrayAdapter 並不好用,可以改用 SimpleAdapter

在 android 專案中 加入 admob


在 Android 專案中加入 admob 的方法可以參考這篇,裡面的步驟1~4是一模一樣的,以我的版權聲名流程為例,程式碼修改為

   1:  package com.example.helloworld;
   2:   
   3:  import android.animation.AnimatorSet;
   4:  import android.animation.ObjectAnimator;
   5:  import android.animation.ValueAnimator;
   6:  import android.annotation.SuppressLint;
   7:  import android.app.Activity;
   8:  import android.app.AlertDialog;
   9:  import android.content.Context;
  10:  import android.content.DialogInterface;
  11:  import android.content.Intent;
  12:  import android.content.pm.ActivityInfo;
  13:  import android.graphics.Typeface;
  14:  import android.net.ConnectivityManager;
  15:  import android.net.NetworkInfo;
  16:  import android.net.Uri;
  17:  import android.os.Bundle;
  18:  import android.view.Gravity;
  19:  import android.view.View;
  20:  import android.view.View.OnClickListener;
  21:  import android.view.Window;
  22:  import android.view.WindowManager;
  23:  import android.widget.Button;
  24:  import android.widget.LinearLayout;
  25:  import android.widget.TextView;
  26:   
  27:  import com.google.ads.AdRequest;
  28:  import com.google.ads.AdSize;
  29:  import com.google.ads.AdView;
  30:   
  31:   
  32:  @SuppressLint("NewApi")
  33:  public class CopyRightFlow extends Activity{
  34:   
  35:      static final String tLog = "Trace Log";
  36:   
  37:      TextView tv; // init by xml use
  38:   
  39:      Button bYes; // enter button
  40:      Button bNo; // exit button
  41:      
  42:      AdView adView;
  43:      
  44:      @Override
  45:      public void onCreate(Bundle savedInstanceState) {
  46:   
  47:          super.onCreate(savedInstanceState);
  48:          
  49:  //        setWindowFeature();
  50:          
  51:          initByXml();
  52:   
  53:      }
  54:      
  55:      void setWindowFeature(){
  56:          //fullscreen
  57:          getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
  58:          //no title
  59:          requestWindowFeature(Window.FEATURE_NO_TITLE);
  60:          //portrait
  61:          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  62:      }
  63:      
  64:      void initByXml() {
  65:          setContentView(R.layout.copyright);
  66:          
  67:          addAdmob();
  68:          
  69:          // TextView init
  70:          tv = (TextView) findViewById(R.id.textView1);// why can't cast to
  71:                                                          // TestTextView
  72:          tv.setTextColor(0xff888888); // set color
  73:          tv.setTextSize(18.0f); // set size
  74:          tv.setTypeface(Typeface.SERIF);// set typeface
  75:          tv.setText(R.string.copy_right);// change text
  76:          tv.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
  77:   
  78:          // ButtonYes init
  79:          bYes = (Button) findViewById(R.id.buttonYes); // get ButtonYes
  80:          OnClickListener bYesOc = new OnClickListener() { // build ButtonYes Listener
  81:   
  82:              @Override
  83:              public void onClick(View v) {
  84:                  // TODO Auto-generated method stub
  85:   
  86:  //                CopyRightFlow.this.finish(); // exit program
  87:  //                
  88:  //                Intent goAct = new Intent();// new a Intent
  89:  //                goAct.setClass(CopyRightFlow.this, GetDisplaySize.class); // setclass
  90:  //                startActivity(goAct); // start another Activity
  91:  //                
  92:  //                System.exit(0);
  93:                  
  94:                  
  95:                  ValueAnimator rotationY = ObjectAnimator.ofFloat(bYes, "rotationY", 0f, 360f);
  96:                  ValueAnimator rotationX = ObjectAnimator.ofFloat(bYes, "rotationX", 0f, 360f);
  97:                  rotationY.setDuration(1000);                
  98:                  rotationX.setDuration(500);
  99:                 
 100:                  AnimatorSet as = new AnimatorSet();
 101:                  as.playTogether(rotationY,rotationX);
 102:                  as.start();
 103:              }
 104:          };
 105:          bYes.setOnClickListener(bYesOc);// set ButtonYes Listener
 106:   
 107:          // ButtonNo init
 108:          bNo = (Button) findViewById(R.id.buttonNo); // get ButtonNo
 109:          bNo.setOnClickListener(new OnClickListener() { // build ButtonNo Listener
 110:   
 111:              @Override
 112:              public void onClick(View v) {
 113:                  // TODO Auto-generated method stub
 114:                  
 115:                  showAlertDialog();
 116:                  
 117:              }
 118:          });
 119:      }
 120:   
 121:      void showAlertDialog(){
 122:   
 123:          AlertDialog ad = new AlertDialog.Builder(this).create();
 124:          
 125:          ad.setTitle("警告");//設定警告標題
 126:          ad.setMessage("確定離開??");//設定警告內容
 127:          ad.setButton("確定", new DialogInterface.OnClickListener() {//設定按鈕1
 128:              
 129:              @Override
 130:              public void onClick(DialogInterface dialog, int which) {
 131:                  
 132:                  //點選按鈕1後執行的動作
 133:                  //檢查網路狀態
 134:                  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 135:   
 136:                  NetworkInfo ni = cm.getActiveNetworkInfo();
 137:                  if (ni == null) {//沒有網路
 138:   
 139:  //                    CopyRightFlow.this.finish();//結束程式
 140:                      System.exit(0);
 141:                  }
 142:                  else if (ni != null) {//若有網路先連結到外部網頁
 143:   
 144:                      if( ni.isConnected()){
 145:                          
 146:                      
 147:                      Uri uri = Uri.parse("http://vulpesadn.blogspot.tw/");
 148:                      Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 149:                      startActivity(intent);
 150:   
 151:  //                    CopyRightFlow.this.finish();//再結束程序
 152:                      System.exit(0);
 153:                      }
 154:                  }
 155:              }
 156:          });
 157:          ad.setButton2("取消", new DialogInterface.OnClickListener() {//設定按鈕2
 158:              
 159:              @Override
 160:              public void onClick(DialogInterface dialog, int which) {
 161:                  
 162:                  //點選按鈕2後執行的動作
 163:                  //無動作
 164:              }
 165:          });
 166:          
 167:          ad.setCanceledOnTouchOutside(false);//當警告提示出現後,點選提示以外範圍,是否會取消提示,預設是true
 168:          
 169:          ad.setCancelable(false);//當警告提示出現後,點選其他實體按鈕(backkey等等),是否會取消提示,預設是true
 170:          
 171:          ad.show();//顯示按鈕
 172:      }
 173:      
 174:      void addAdmob() {
 175:   
 176:           adView = new AdView(this, AdSize.BANNER, "xxxxxxxxxxxxxxx");//xxxxxxxxxxxxxxx is your admob id    
 177:           LinearLayout layout = (LinearLayout) findViewById(R.id.AdLayout);
 178:           layout.addView(adView);
 179:           adView.loadAd(new AdRequest());
 180:   
 181:      }
 182:  }

第 42 行產生 AdView 的 reference, adview
第 67 行為建立 admob 廣告的方法,其內容定義在 174 ~ 181 行
第 176行產生 adview 物件,其中 xxxxxxxxxx 為你的發布商id
第 177 行使用 LinearLayout 佈局,這個佈局專門給 adview 使用
第 178 行加入 adview
第 179 行要求 顯示廣告

程式碼的部分是如此,接著請注意 addAdmob 方法是在 setContentView 後呼叫代表在 R.layout.copyright 必須加入給 adview 使用的 佈局,所以 R.layout.copyright 修改如下

   1:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   2:      xmlns:tools="http://schemas.android.com/tools"
   3:      android:layout_width="match_parent"
   4:      android:layout_height="match_parent" >
   5:   
   6:      <TextView
   7:          android:id="@+id/textView1"
   8:          android:layout_width="wrap_content"
   9:          android:layout_height="wrap_content"
  10:          android:layout_centerHorizontal="true"
  11:          android:layout_centerVertical="true"
  12:          android:text="@string/hello_world" />
  13:   
  14:      <Button
  15:          android:id="@+id/buttonYes"
  16:          android:layout_width="wrap_content"
  17:          android:layout_height="wrap_content"
  18:          android:layout_alignParentBottom="true"
  19:          android:layout_alignParentLeft="true"
  20:          android:text="繼續" />
  21:   
  22:      <Button
  23:          android:id="@+id/buttonNo"
  24:          android:layout_width="wrap_content"
  25:          android:layout_height="wrap_content"
  26:          android:layout_alignParentBottom="true"
  27:          android:layout_alignParentRight="true"
  28:          android:text="離開" />
  29:   
  30:      <LinearLayout
  31:      android:id="@+id/AdLayout"
  32:      android:layout_width="wrap_content"
  33:      android:layout_height="wrap_content"
  34:      ></LinearLayout>
  35:      
  36:  </RelativeLayout>

第 30 ~ 34 行就是新加入的佈局專門給 adview 使用,如果就這樣執行的話,廣告會顯示,不過你會看到1個奇怪的內容如下



















提示你必須在 AndroidManifest.xml 中建立 adactivity 以及使用 configChanges ,所以我們就跟著提是修改 AndroidManifest.xml 吧

在 <application>標籤中加入

   1:          <activity android:name="com.google.ads.AdActivity"
   2:          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

第 1 行建立 AdActivity
第 2 行使用指定的 configchanges

最後還要記得開網路,不然廣告也無法顯示
結果為




Eclipse 中 android 專案出現紅色驚嘆號


在複製原專案時,若有使用到外部 jar 檔,但在新專案的 Java Build Path 卻沒有包含原專案的jar 檔,很容易出現這種錯誤,解決方法就把原專案需要的 jar 檔包含在新專案中

存取資料 part2 (FileOutputStream & FileInputStream)


FileOutputStream 和 FileInputStream 是位於 java.io 的套件中,屬於 java 本身的 io 方法,使用這種方式儲存的資料無法提供給別的應用程式,而且當應用程式移除後資料也會隨之消失,範例如下

寫入資料

   1:          try {
   2:                  file = new File("test_file");
   3:              
   4:                  FileOutputStream fos = openFileOutput(file.getPath(), Context.MODE_PRIVATE);
   5:                  String tempstr = "abc";
   6:                  int tempint = 123;
   7:                  float tempfloat = 0.88f;
   8:                  
   9:                  fos.write(tempstr.getBytes());
  10:                  fos.write(String.valueOf(tempint).getBytes());
  11:                  fos.write(String.valueOf(tempfloat).getBytes());
  12:                  
  13:                  fos.close();
  14:              } catch (FileNotFoundException e) {
  15:                  // TODO Auto-generated catch block
  16:                  e.printStackTrace();
  17:              } catch (IOException e) {
  18:                  // TODO Auto-generated catch block
  19:                  e.printStackTrace();
  20:              }


第 2 行設定檔名
第 4 行建立 FileOutputStream 物件
第 5 ~ 7 行要寫入的資料
第 9 ~ 11 行寫入資料
第 13 行關閉 FileOutputStream 物件

這樣就完成寫入的動作,在手機內部會產生 test_file 檔案


讀取資料

   1:          try {
   2:              FileInputStream fis = openFileInput(file.getPath());
   3:              
   4:              int temp;
   5:              
   6:              while((temp = fis.read()) !=-1){
   7:                  FP.p(String.valueOf(((char)temp)));
   8:              }
   9:              
  10:              fis.close();
  11:              
  12:          } catch (FileNotFoundException e) {
  13:              // TODO Auto-generated catch block
  14:              e.printStackTrace();
  15:          } catch (IOException e) {
  16:              // TODO Auto-generated catch block
  17:              e.printStackTrace();
  18:          }


第 2 行建立 FileInputStream 物件, file.getPath() 為檔名
第 4 行用來暫存資料
第 6 行讀取檔案
第 10 行關閉 FileInputStream 物件






Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews