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






存取資料 part1 (SharedPreferences)


如果只想存取單純的資料,如 Int , String 等等,這些基本型態可以使用 SharedPreferences 這個介面,使用簡單不過也有限制,只接受基本型態的資料存取如 Int , Float , Boolean , Long , String,也只能提供單個應用程式使用,使用的方式如下

讀取資料

   1:          SharedPreferences loadsp = getPreferences(0);
   2:          
   3:          int loadint = loadsp.getInt("testint", 1);
   4:          boolean loadboolean = loadsp.getBoolean("testboolean", false);

第 1 行藉著 Activity 的 getPreferences() 方法產生 loadsp 物件
第 3 行使用 getInt() 取得儲存數值, testint 為 key , 當 key不存在時設定 1 為預設值,
第 4 行類似的方法取的布林值

儲存資料

   1:          SharedPreferences loadsp = getPreferences(0);
   2:          SharedPreferences.Editor savese = loadsp.edit(); 
   3:          
   4:          savese.putInt("testint", 99);
   5:          savese.putBoolean("testboolean", true);
   6:          
   7:          savese.commit();

第 1 行建立 SharedPreferences 物件
第 2 行建立 SharedPreferences.Editor 物件,來進行儲存的動作
第 4 行儲存 int 數值,參數 1 為 key ,參數 2 為 value
第 5 行儲存 boolean
第 7 行執行上述的儲存動作,若無此行就不會儲存

使用 SharedPreferences 來儲存的機會,多是小而簡單的資料,它提供 key - value 的儲存方式,使用起來也很直覺

注意事項:
若是使用 getPreferences 來取得紀錄,那麼該記錄只能給呼叫的 activity 使用,即使是同一個套件中的另一個 activity 也無法取得記錄,所以建議使用 getSharedPreferences("name", 0); 使用這個方法指定名稱後,不同的 activity 就能取得記錄

切換 Activity 的簡單轉場動畫(overridePendingTransition)


在這篇中有提到 ViewAnimator 的用法,其作用在比較複雜的動畫上,如果只是想達到 Activity 之間簡單的轉場的話可以使用

overridePendingTransition(activity_enter, activity_exit);

這個方法,它是 Activity 的方法,作用在 startActivity() 或 finish() 之後,第1個參數為下1個Activity進入的動畫,第2個參數為上1個Activity離開的動畫,必須注意參數只接受在 xml 中定義好的動畫,如何定義1個簡單的動畫呢,如下

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

就是簡單的淡入動畫,裡面定義改變的alpha值,動畫時間,最後在放入方法中即可,以我的Logo流程切換為例如下

   1:                  LogoFlow.this.finish(); // close activity
   2:                  sleeping = true;// stop Thread
   3:                  Intent goAct = new Intent();// new a Intent
   4:                  goAct.setClass(LogoFlow.this, CopyRightFlow.class); // set another activity
   5:                  startActivity(goAct); // start another Activity
   6:                  
   7:                  overridePendingTransition(R.anim.fadeout, R.anim.zoom_exit);//使用過場,第1個參數是下1個場景的進入,第2個參數是本身場景的離開
   8:                  
   9:                  System.exit(0);// stop program


第7行就是使用 overridePendingTransition 方法,動畫還有不少組合可以使用如下

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <set xmlns:android="http://schemas.android.com/apk/res/android"
   3:          android:interpolator="@android:anim/decelerate_interpolator"
   4:          android:zAdjustment="top">
   5:      <scale android:fromXScale="1.0" android:toXScale=".5"
   6:             android:fromYScale="1.0" android:toYScale=".5"
   7:             android:pivotX="50%p" android:pivotY="50%p"
   8:             android:duration="@android:integer/config_mediumAnimTime" />
   9:      <alpha android:fromAlpha="1.0" android:toAlpha="0"
  10:              android:duration="@android:integer/config_mediumAnimTime"/>
  11:  </set>

這是使用set標籤組合2個不同的動畫(縮小和淡出)

Twitter Delicious Facebook Digg Stumbleupon Favorites More

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