2012年10月23日

找尋 NSString 字串裡的某一個字或某一段字,將之取代為另一個字或另一段字


找尋字串裡是否含有某一個字或某一段文字,如果確定找到,將之取代為另一個字或另一段文字:

e.g.
I am in a bad mood.  ==>  I am in a good mood.
我今天心情很。  ==>   我今天心情很

*************************************************

- (void) viewDidLoad {

NSString *original = @"I am in a bad mood.";

NSLog (@"After replace, the result = %@", [self replaceStringWithSomeCharacters: original]);

}

- (NSString *) replaceStringWithSomeCharacters : (NSString *) aString{
    
 // 1. 定義要換掉的字串
    NSRange search = [aString rangeOfString:@"bad" options:NSCaseInsensitiveSearch];
  
//2. 建立一個新字串,值為 ""
    NSString *afterReplace = @"";

//3. 如果有找到要替換的"bad"
    if (search.location != NSNotFound) {

//4. 以"good" 替換掉 search 
        afterReplace = [aString stringByReplacingCharactersInRange:search withString:@"good"];

//5. 回傳替換後的結果
        return afterReplace;
    }
  
//4. 字串中找不到有"bad"的地方,回傳原來的字串
    return aString;
}

2012年10月7日

iOS -- different fonts and colors in a NSString 字串裡可以有不同的字體和顏色



讓某一個 NSString 裡可以有不同的 font 和顏色

                 



iOS 3.2 以後   iOS 6 以前  如果要達到這樣的效果,可以試一試下列的步驟:

1. 加入 CoreText.framework
2、匯入 TTTAttributedLabel.h  和  TTTAttributedLabel.m 到你的 Xcode Project
3、不要使用 UILabel; 改用 TTTAttributedLabel 的 class



QQViewController.h


#import <UIKit/UIKit.h>
#import "TTTAttributedLabel.h"

@interface QQViewController : UIViewController 
@property (strong, nonatomic) TTTAttributedLabel *label;

@end

QQViewController.m
#import "QQViewController.h"

@implementation QQViewController
@synthesize label;

- (void)viewDidLoad
{
    [super viewDidLoad];

//定義標籤框Label 的一些參數
    label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(10, 20, 200, 100)];
    label.font = [UIFont systemFontOfSize:18];
    label.textColor = [UIColor blueColor];
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.numberOfLines = 0;
    
    NSString *text = @"Lorem ipsum dolar sit amet";
    

    [label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {

    //SET 3 different RANGES  設定一字串中有三個不同的範圍
    NSRange frontRange = [[mutableAttributedString string] rangeOfString:@"Lor" options:NSCaseInsensitiveSearch];
        
    NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"ipsum dolar" options:
            NSCaseInsensitiveSearch];

    NSRange aStressRange = NSMakeRange(24, 1);

        //SET FONT 設定字體
        //粗體
        UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:18];
        CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
        //斜體
        UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:18];
        CTFontRef italicFont = CTFontCreateWithName((__bridge CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL);
        
        if (font) {
            //第一段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:frontRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
              (__bridge id)italicFont range:frontRange];
            
            //第二段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:boldRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
            (__bridge id)font range:boldRange];
           
            //第三段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:aStressRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
            (__bridge id)font range:aStressRange];
            
            //自定字體
            // [mutableAttributedString addAttribute:@"TTTCustomStrikeOut" value:[NSNumber
            //  numberWithBool:YES] range:aStressRange];
            
            CFRelease(font);
        }  //end of font

        
       //SET COLOR
        //第一段範圍的字體顏色
        [mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName 
          value:(id)[[UIColor greenColor] CGColor] range:frontRange];


        //第二段範圍的字體顏色
         [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName 
          value:(id)[[UIColor grayColor] CGColor] range:boldRange];
        
         //第三段範圍的字體顏色
        [mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName 
          value:(id) [[UIColor redColor] CGColor] range:aStressRange];
        
        
        //SET CAPITAL
        [mutableAttributedString replaceCharactersInRange:boldRange withString:
          [[[mutableAttributedString string] substringWithRange:boldRange] uppercaseString]];
        
        return mutableAttributedString;
    }];
    
    [self.view addSubview:label];
    
    
    
}






iOS --.xlsx 檔轉成 .csv 檔,準備之後轉成 sqlite檔使用

以 mac 的作業系統為例:
將 excel 的 .xlsx 檔轉成 .csv 的步驟:

1. 建立一個 .xlsx 檔

 
 
 2. 另存成 .csv 檔

 3. 以 text 瀏覽器打開,在此我使用 TextWrangler 。到 Edit --> Document Options:
     
             
 4. 將它 copy 入 Xcode 的 project 裡以用建立 sqlite 檔使用。
     要確定 .csv 檔在 project 裡沒問題,可以點它,看中文有無亂碼:
     如果見到如下,就沒問題:

     學生;國文;英文
     John;89;90
     Mary;56;83
     Peter;78;54


*PS 在 .xlsx 裡輸入資料時,請不要用英文的分號 (;)。如果真的需要分號,請以中文的方式輸入(;)。這樣才能確保在程式裡轉檔成sqlite檔案時不會出問題!!!

 
 


iOS -- sqlite3 的使用順序 & query 例子



使用 sqlite3 的一般步驟:


sqlite3_open()        Open the database  打開資料庫
sqlite3_prepare()     Create the SQL statement  準備建立好的資料庫指令 (query)
sqlite3_step()        Execute the statement  執行指令
sqlite3_column()      Fetch the result  取得結果
sqlite3_finalize()    Destroy the statement  銷燬指令
sqlite3_close()       Close the database  關閉資料庫


query 例子:
1. CREATE  TABLE "main"."STARS" ("Rowid" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "Star" VARCHAR, "image" BLOB)


2. SELECT DISTINCT [column_name] FROM [table_name];

3. SELECT * FROM * WHERE * LIKE %$value%;

4. 找幾筆資料 (no. of rows in the table):
NSString *query = [NSString stringWithFormat:@"SELECT COUNT(%@) FROM %@ ", kSelectedColumn, kTablename];
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(database, [query UTF8String] , -1, &stmt, nil) == SQLITE_OK) {
     
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int noOfRows = (int) sqlite3_column_int(stmt, 0);
            NSLog(@"%d", noOfRows);
        }
        sqlite3_finalize(stmt2);
    } else NSLog(@"never entered!!!");
    sqlite3_close(database);



Fetch 的例子:

int sqlite3_column_count(sqlite3_stmt *pStmt);


可參考:http://www.sqlite.org/capi3ref.html

iOS -- NSString 轉 C string and vise versa



// 從 NSString 轉成 char (C 語言物件:C string):

   NSString *aStr = @"Hello CQ!";
   const char *update = [aStr cStringUsingEncoding:NSUTF8StringEncoding];
   printf("%s\n",  update);

或是:

e.g. 1
const char *ptr2 = [aStr UTF8String];
printf("%s\n", ptr2);



e.g. 2 (適用在建立 sqlite3 的query)

NSString *query = [NSString stringWithFormat:@"SELECT %@ FROM %@ WHERE %@ = %@ ORDER BY %@, destinationColumn, aTablename, aColumn, aString, ROWID";
    const char * sql = [query UTF8String];


********************************

// C string 轉  NSString

ptr = "C string to string object";
NSString *str = [NSString stringWithCString:ptr encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);





2012年6月28日

如何在iOS讀出繁體中文的檔案


如何在iOS讀出繁體中文的檔案:

準備兩個檔;一個是以Big5寫的, e.g. translation01.txt
                     另一個是以UTF-8寫的,e.g. UTF8.txt





#import <Foundation/Foundation.h>

/** 讀出中文檔案內容 **/

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSLog(@"** begin **");
        NSString * strBig5, *strUTF8, *strUTF_8;
               
        //Big5
        NSLog(@"\n\n** 這是繁體中文Big5的實驗 **");
         NSStringEncoding encBig5 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingBig5);
        strBig5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/translation01.txt" encoding:encBig5 error:nil];//OK
         NSLog(@"%@\n\n", strBig5);
        
        
        //UTF─8
        NSLog(@"** 這是繁體中文UTF-8的實驗 **");
        strUTF_8 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/UTF8.txt" encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"%@\n\n", strUTF_8);
        
        
        //UTF8:舊式
        NSLog(@"** 這是UTF8的實驗(舊式) **");
         NSStringEncoding encUTF8 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
        strUTF8 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/UTF8.txt" encoding:encUTF8 error:nil];
        NSLog(@"%@", strUTF8);
        
        
       
    }
    
    return 0;
}

結果:


2012-06-28 22:51:53.146 InitiationChap10[912:903] ** begin **
2012-06-28 22:51:53.150 InitiationChap10[912:903] 
** 這是繁體中文Big5的實驗 **
2012-06-28 22:51:53.160 InitiationChap10[912:903] 1.她是像天使般的女性。
She is an angel of a woman.
2.排山巨浪湧過來了。
A mountain of a wave came near.
3.這幾乎是不可能的。
This is all but impossible.
4.她就像是死了一樣。
She is all but dead.
5.他們並非全部都滿意這項結果。
All of them were not satisfied with the result.
2012-06-28 22:51:53.161 InitiationChap10[912:903] ** 這是繁體中文UTF-8的實驗 **
2012-06-28 22:51:53.162 InitiationChap10[912:903] 這是utf8的實驗,希望能顯示繁體中文。
2012-06-28 22:51:53.164 InitiationChap10[912:903] ** 這是UTF8的實驗(舊式) **
2012-06-28 22:51:53.165 InitiationChap10[912:903] 這是utf8的實驗,希望能顯示繁體中文。
Program ended with exit code: 0



P.S.
簡體中文的話,得改成:kCFStringEncodingGB_18030_2000

2012年5月31日

網路檔案下載─FTP



網路檔案下載─FTP: 從中華電信提供的網路存放空間,下載檔案。

使用外部元件: Apache Commons NET
   commons-net-3.0.1-src.zip 的class : 下載點

     1. Unzip it.
     2. 到Eclipse的android作業平台上的 File -> Import -> General -> File System
    

          

       3. 然後 Browse 剛才Unzip後 存放 commons-net-3.0.1-src 的夾子,找到 java 的子目錄,然後按『確定』。

4. 你的作業環境,應該會呈現下圖的樣子,如果如圖所示,表示成功,便可以開始使用了。





需開啟之權限: 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>


main.java


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class FTPDownloadFileActivity extends Activity {
    /** Called when the activity is first created. */

private TextView tv;
private TextView tvContent;
private String fileName = "myFile.txt"; //網站上準備要下載的檔名


private final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/download";
private final String FILE_NAME = "copy_" + fileName; //下載進手機後的檔名
private final String ENCODING = "UTF-8";
private FileInputStream fis = null;


        private ProgressDialog mProgressDialog;
 
private Handler handler = new Handler(){  //使用handler, thread 防止下載檔案太大

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
mProgressDialog.dismiss(); //close
readFile();
}

};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tv = (TextView)findViewById(R.id.textview);
        tvContent = (TextView) findViewById(R.id.textviewContent);
        processThread();
     
    }
 
 
 
    private void ftpDownload() {  //使用FTP 下載檔案
    FTPClient ftpClient = new FTPClient();
    try {
//     ftpClient.connect(InetAddress.getByName("203.66.87.21"));//與以下的String 意義一樣
    ftpClient.connect(InetAddress.getByName("ftp.myweb.hinet.net")); //中華電信的網頁IP ADDRESS
    ftpClient.login("username", "password");
    tv.setText(String.valueOf(ftpClient.isConnected()));
    ftpClient.changeWorkingDirectory("/");
    File localfile = new File ("/sdcard/download/" + FILE_NAME);
    OutputStream os = new FileOutputStream(localfile);
    ftpClient.enterLocalPassiveMode();
    ftpClient.retrieveFile(fileName, os);
    ftpClient.logout();
    ftpClient.disconnect();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
 
 
    public void readFile () {  //將內容顯示到螢幕上
     
        String result = "";
        try {
       
         File mFilePath = new File (SD_PATH + FILE_PATH);
         String mFileName = mFilePath + "/" + FILE_NAME;
         File fileText = new File (mFileName);
       
         fis = new FileInputStream(fileText);
         int length = fis.available();
         byte [] buffer = new byte [length];
         fis.read(buffer);
         result = EncodingUtils.getString(buffer, ENCODING);
         fis.close();
         tvContent.setText(result);
       
        } catch (Exception e) {
         e.printStackTrace();
        }
       }
 
 
    private void processThread() {
    mProgressDialog = ProgressDialog.show(this, "文件下載", "正在下載...");
    new Thread () {

@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
ftpDownload();
prolongedActionMethod(); //做測試用的
handler.sendEmptyMessage(0);
}
   
    }.start();
    }
 
 
    private void prolongedActionMethod() { //故意延遲十秒鐘,做測試用的
    try {
    Thread.sleep(10000);
    }catch (Exception e){
    e.printStackTrace();
    }
    }
}


*************************************************
res/layout/main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    <!--  將 TextView 包在 ScrollView 裡,當內容太長,可以捲動。  -->
     <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadingEdge="vertical"
        android:paddingTop="10dip"
        android:scrollbars="vertical" >

        <TextView
            android:id="@+id/textviewContent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text=""
            android:textSize="20dp"
            android:textColor="#00FF00" />
    </ScrollView>

</LinearLayout>

2012年5月30日

背景:重複動畫




重複讓背景淡出、深入的動作:





import android.app.Activity;
import android.os.Bundle;

import android.view.animation.Animation;
import android.view.animation.AnimationUtils;


import android.widget.LinearLayout;

public class BackgroundDemoActivity extends Activity {

    private LinearLayout mLinearLayout;
    private Animation alphaAnim;


   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        mLinearLayout = (LinearLayout) findViewById(R.id.LinearLayout01);
        alphaAnim = AnimationUtils.loadAnimation(this, R.anim.alpha);
        mLinearLayout.setAnimation(alphaAnim);
      }
}


************************************************
res/anim/alpha.xml:


<?xml version="1.0" encoding="utf-8"?>
<set android:shareInterpolator="false" xmlns:android="http://schemas.android.com/apk/res/android">
   <alpha android:fromAlpha="1.0"
        android:toAlpha="0.6"
        android:startOffset="0"
        android:duration="5000"
        android:repeatCount="infinite"
        android:repeatMode="reverse"
        />
</set>
********************************
res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/gradient_selector"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

*********************************
res/drawable/gradient_selector.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape>
            <gradient 
                android:angle="90" 
                android:endColor="#FF00FF00" 
                android:startColor="#FFFF0000" 
                android:type="linear" />
        </shape>
        
     </item>

</selector>

**********************************************
**********************************************
當然也可以換成:traslate

res/anim/translate.xml:


<?xml version="1.0" encoding="utf-8"?>
<set android:shareInterpolator="false" xmlns:android="http://schemas.android.com/apk/res/android">

    <scale android:fromXScale="1"
          android:toXScale="5"
          android:fromYScale="1"
          android:toYScale="5"
          android:pivotX="50%"
          android:pivotY="50%"
          android:duration="3000"
          android:repeatCount="infinite"
 android:repeatMode="reverse"/>
 
<translate
android:fromXDelta="0"
android:toXDelta="20"
android:fromYDelta="0"
android:toYDelta="20"
android:startOffset="10"
android:duration="3000"
android:repeatCount="infinite"
android:repeatMode="reverse" />

</set>


***********************************************
***********************************************
或是
res/anim/rotate.xml:


<?xml version="1.0" encoding="utf-8"?>
<set android:shareInterpolator="false" xmlns:android="http://schemas.android.com/apk/res/android">

    <scale android:fromXScale="3"
          android:toXScale="3"
          android:fromYScale="3"
          android:toYScale="3"
          android:pivotX="50%"
          android:pivotY="50%"
          android:duration="5000"
          android:repeatCount="infinite"
 android:repeatMode="restart"/>
    <rotate
        android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
android:pivotY="50%"
  android:startOffset="10"
android:duration="5000"
android:repeatCount="infinite"
android:repeatMode="restart"/>
 
</set>

2012年5月19日

TextView 滾動 ─利用 ScrollView


只要用 ScrollView 包起來,TextView 裡的內容便可以滾動。



res/layout/main.xml:



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="測試 TextView 的內容可以滾動"
        android:textSize="25dp" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadingEdge="vertical"
        android:paddingTop="10dip"
        android:scrollbars="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/text_content"
            android:textSize="20dp" />
    </ScrollView>

</LinearLayout>

*******************************

res/values/strings:

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

    <string name="hello">Hello World, Cq_TextView01Activity!</string>
    <string name="app_name">Cq_TextView01</string>
    <string name="text_content">歐美經濟情勢動盪不安,連帶影響國際油價持續走跌,預計台灣中油於下周一起,汽柴油價格可望降價1角,是從上個月油價調漲後,連續第7次調價。
現在的92無鉛汽油每公升是32.6元,自4月2日一次調漲2.3元;而95無鉛每公升為34.1元,從4月2日一次調升3.1元;此外,98無鉛每公升為36.1元,4月2日則一次增3.6元;柴油每公升是31.7元,4月2日一次調漲3.2元。
國際油價走跌,指標原油價格自上周每桶109.92美元跌到108.67美元;依據浮動油價公式以及減半調降機制初步估計,台灣中油從下周一凌晨起,可望再度調降國內汽柴油的價格,每公升調降約1角。
    </string>

</resources>



2012年5月18日

Text String 變色




Text String




public class TextViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        TextView tv = new TextView (this);
        String string = "Ilovemydog"; //10 letters
        SpannableStringBuilder fontStyleBuilder = new SpannableStringBuilder(string);
        fontStyleBuilder.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //1-0 = 1 letter-> I
        fontStyleBuilder.setSpan(new ForegroundColorSpan(Color.RED), 1, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//5-1 = 4 letters-> love
        fontStyleBuilder.setSpan(new ForegroundColorSpan(Color.GREEN), 5, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//7-5 = 2 letters -> my
        fontStyleBuilder.setSpan(new ForegroundColorSpan(Color.YELLOW), 7, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//10-7 = 3 letters -> dog
        tv.setText(fontStyleBuilder);
        tv.setTextSize(24);
        setContentView(tv);
    }
}

2012年3月12日

String to Drawable



String 轉 drawable:

e.g. 1


private void displayImage() {

String uri = "drawable/imagefile01"; 
 // int imageResource = R.drawable.icon; 
int imageResource = getResources().getIdentifier(uri, null, getPackageName()); 
ImageView imageView = (ImageView) findViewById(R.id.myImageView); 
Drawable image = getResources().getDrawable(imageResource); imageView.setImageDrawable(image);
 }

***********************************************

e.g.2 應用在 database + ListAdapter
假設圖檔放在 res/drawable/ 下,其檔名則是以字串方式存在 database 裡。可以下列方式將之顯現出來:



Cursor c = getData();
c.moveToFirst();

String [] imgStrings = new String [c.getCount()]; //將存放從db來的圖檔名
int [] imgResources = new int [c.getCount()];//準備將字串轉成整數格式 
Object [] imgObj = new Object [c.getCount()];//準備接收成 Drawable 的物件

for (int i = 0; i < str1.length; i++){
  imgStrings [i] = c.getString(0);//圖形檔名後接有 .png
 //將存在db的圖檔字串檔名轉成drawable
 String uri = "drawable/" + str2[i].substring(0, str2[i].length()-4).toString(); 
 // 刪掉後頭的 .png (四個位元)
 imgResources[i] = getResources().getIdentifier(uri, null, getPackageName());
 imgObj [i] = getResources().getDrawable(imgResources[i]);
c.moveToNext();
}
c.close(); 
/CustomAdapter. 將得到的drawable 物件陣列,傳入自己設定的adapter 
ArrayAdapter<String> adapter = new CustomAdapter(this, imgObj); 
setListAdapter(adapter);


&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&


CustomAdapter.java 自己設定的 Adapter:

public class CustomAdapter extends ArrayAdapter<String>{

 private LayoutInflater inflater;
 private final Context context;

private final Object [] img; //來接收傳進來的drawable 物件陣列

public EventAdapter(Context context, Object [] imgObj) { //Constructor
 super(context, R.layout.eventlayout, event);
 this.context = context; 
 this.img = imgObj;
}
@Override

public View getView(int position, View convertView, ViewGroup parent) {

   ViewHolder holder = new ViewHolder(); 
   inflater = LayoutInflater.from(context); 
   View rowview = inflater.inflate(R.layout.eventlayout, parent, false);
   holder.imageview = (ImageView)rowview.findViewById(R.id.ImageView01); 
   Object drawable = img[position]; //將Object 型態轉為 Drawable
   holder.imageview.setImageDrawable((Drawable) drawable);
   return rowview;
   } 

    static class ViewHolder
    ImageView imageview;
    }

}

去字串的字元

如果刪除字串的某些字元:



設定某一字串:
String aStr = love;

str = aStr.substring(0, str.length()-0).toString(); // ==> love
str = aStr.substring(0, str.length()-1).toString(); // ==> lov
str = aStr.substring(0, str.length()-2).toString(); // ==> lo
str = aStr.substring(0, str.length()-3).toString(); // ==> l

OR   
str = aStr.substring(0, 1).toString();//l
str = aStr.substring(0, 2).toString();//lo
str = aStr.substring(0, 3).toString();//lov
str = aStr.substring(0, 4).toString();//love






只要取 "crazy" (紅色的部分─12個字元不要):
String aStr = "irrevocably-crazy";

str = aStr.substring(12, aStr.length());   第一個參數是從第幾個字元開始;第二個參數是到哪個字元結束


如果
aStr = "love." 為了要去掉最後的句點  str = aStr.substring (0, aStr.length()-1).toString();

2012年2月28日

android-- change display color (A)

靜態改變顯示顏色的方法:

           




  1、在 res/values 的目錄下,再建立一個 color.xml 檔,編輯會用到的顏色如下:
                     
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#FF0000</color>
<color name="cyan">#00FFFF</color>
<color name="blue">#0000FF</color>
<color name="darkBlue">#0000A0</color>
<color name="lightBlue">#ADD8E6</color>
<color name="purple">#800080</color>
<color name="yellow">#FFFF00</color>
<color name="lime">#00FF00</color>
<color name="fuchsia">#FF00FF</color>
<color name="white">#FFFFFF</color>
<color name="silver">#C0C0C0</color>
<color name="gray">#808080</color>
<color name="black">#000000</color>
<color name="orange">#FFA500</color>
<color name="brown">#A52A2A</color>
<color name="maroon">#800000</color>
<color name="green">#008000</color>
<color name="olive">#808000</color>

</resources>


   2、在 main.xml 檔裡,加上:

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


                 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical"
                    android:background="@color/purple">  <!-- 改變背景色 -->

                       <TextView
                         android:layout_width="fill_parent"
                         android:layout_height="wrap_content"
                         android:text="我是黃色  " 
                         android:textColor="@color/yellow"  <!-- 改變文字欄位顏色 -->
                         />

                       <TextView
                         android:layout_width="fill_parent"
                         android:layout_height="wrap_content"
                         android:text="我是亮綠色  " 
                         android:textColor="@color/lime" <!-- 改變文字欄位顏色 -->
                         />

                 </LinearLayout>






2012年2月27日

Customized ListView Adapter -- 自定 ListView Adapter

Customized ListView Adapter  自定 ListView Adapter:

如果能自訂自己喜歡的ListView樣式,如下圖一樣,那一定是很不錯的感覺:



要達到上圖的效果,基本上只要做三件事,便大功完成:
  1、建立自己的adapter(MyCustomListViewAdapter.java)來連接(2)的xml;
  2、建立自己喜歡的單欄樣版(rowlayout.xml):
  3、在主程式上(Cq_MyListViewExampleActivity),將 main.xml 裡的 listview1 連接上自己製作的 adapter.
                                                     全部需要準備的檔如下:



(一)建立自已的adapter:
MyCustomListViewAdapter.java:

package com.cq.listview.example;

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
 MyCustomListViewAdapter extends ArrayAdapter<String>{

private final Context context;
private final CharSequence[] values1; //建立兩個參數陣列來接收主程式傳進來的兩個陣列
private final CharSequence [] values2;

   //建構子
   public MyCustomListViewAdapter(Context context, String [] strValues1, String [] strValues2) {
           super(context, android.R.layout.simple_list_item_1, values1);
          // TODO Auto-generated constructor stub
             this.context = context;
             this.values1 = strValues1;
             this.values2 = strValues2;
   }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      // TODO Auto-generated method stub
          //取得.xml layout檔的資源,用來放入自設的欄位樣式( rowview)
          LayoutInflater inflater =
              (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             
          View rowview = inflater.inflate(R.layout.exampleLayout, parent, false);

          TextView textview = 
                 (TextView)rowview.findViewById(R.id.textview01);  //連接上自設的樣式元素
          ImageView subtopicImageView = 
                (ImageView)rowview.findViewById(R.id.imageview01);

          String s1 = values1[position].toString(); //依次傳入值
          String s2 = strValues2[position].toString();

           //交錯圖檔
          if ((position + 2)%2 == 0){
                   imageview01.setImageResource(R.drawable.basketball);
                   }else if ((position + 2)%2 == 1){
                   imageview01.setImageResource(R.drawable.americanfootball);
                   }
         
           //將傳入的值顯示在textview上
           textview.setText(s1 + "  " + s2);

           return rowview; //傳出單一整個欄位的設置
           }

}

*********************************************
(二)、建立自己喜歡的單欄樣版:

照自己喜歡的方式,準備自定的樣式layout給自定的 listview 用 (如下: rowlayout.xml)。
請準備兩個圖檔(.png),例如basketball.png, tennisball.png
rowlayout.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" >

    <ImageView
        android:id="@+id/imageview01"
        android:layout_width="30px"
        android:layout_height="30px"
        android:layout_marginLeft="4px"
        android:layout_marginRight="10px"
        android:layout_marginTop="4px"
        android:src="@drawable/americanfootball" >
    </ImageView>

    <TextView
        android:id="@+id/textview01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:textColor="@color/orange"
        android:textSize="20px" >
    </TextView>

</LinearLayout>


*********************************************************************

(三)、在主程式上,將 main.xml 裡的 listview 連接上自己製作的 adapter.
MainActivity.java (Cq_MyListViewExampleActivity)有兩個自定的String 陣列
(String [] firstStringArray, String [] secondStringArray)的參數,
將用來傳入以下的自設ListView Adapter:



package com.cq.listview.example;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class Cq_MyListViewExampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //建立兩個字串陣列
        String [] firstStringArray = {"蘋果", "香吉士", "奇異果", "西洋梨", "西瓜", "哈密瓜"
                                                   "葡萄", "杏子", "琵琶", "甘蔗"};
        String [] secondStringArray = {"apples", "oranges", "kiwi", "pears", "watermelon"
                                                      "cantaloupe", "grapes", "apricots", "loquats", "sugar cane" };
        
        //設ListView參數用以連結.xml的listview
        ListView listview = (ListView)findViewById(R.id.listView1);

        //自設的接口
        MyCustomListViewAdapter adapter = new MyCustomListViewAdapter(this
                             firstStringArray, secondStringArray);

        //將接口連接到ListView的參數
        listview.setAdapter(adapter);
    }
}


***********************************************************************
  附上 main.xml 檔的內容:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="ListView Example 3" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>