2012年8月18日 星期六

俄文新聞 + ClickableSpan and WebView

閱讀有註解的俄文新聞
Using ClickableSpan and WebView

public class LangRusReaderActivity extends Activity {
    /** Called when the activity is first created. */
private TextView tv;
private static WebView wv;
private String str = "Головной ракетный крейсер четвертого поколения \"Юрий Долгорукий\" " +
"поднимет Андреевский стяг как боевая единица российского ВМФ уже в июле. И день флота " +
"его экипаж встретит в месте постоянного базирования. Будет это Вилючинск на Камчатке или " +
"Западная Лица на Кольском полуострове, пока не уточняется. Но в Минобороны, в Объединенной " +
"судостроительной корпорации и на \"Севмаше\" уже не скрывают: первенец в серии подводных " +
"ракетоносцев, созданных по проекту 955 \"Борей\" санкт-петербургского ЦКБ \"Рубин\", завершает" +
" финальный этап испытаний в Белом море.";
private String [] strings; //To every word in the str into an string array
private String result=""; //To de-array "strings[]" into a string
private CharSequence text; //For spannable use
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        initiation();
        toHtmlFormat();
        toSpannableString ();
    }
    
    
    private void initiation () {
    tv = (TextView) findViewById(R.id.textview01);
    tv.setTextSize(20);
    tv.setLinkTextColor(Color.BLUE);
    tv.setMovementMethod(LinkMovementMethod.getInstance());
    
    wv = (WebView) findViewById(R.id.webView);
    wv.setWebViewClient(new WebViewClient()); //Create
    WebSettings ws = wv.getSettings(); // Get obj
    ws.setJavaScriptEnabled(true);
    
    ws.setSupportZoom(true);
    ws.setBuiltInZoomControls(true);
    
    wv.clearCache(true);
    wv.canGoBack();
    wv.canGoForward();
    
    }
    
  //Rearrange the text into the HTML format
    private void toHtmlFormat () {
    strings = TextUtils.split(str, " ");
    //clear empty space on both sides of a word if any
    for (int i=0; i<strings.length; i++) {
    String temp = "";
    temp = strings[i].trim();
    temp = "<a style='color:yellow' href='" + temp + "'> "+ temp + "</a>"; // Turn into HTML format
    strings[i] = temp;
    }
    
    for (int i=0; i<strings.length; i++) {
    result += strings[i];
    }
    
    tv.setText(Html.fromHtml(result));
    
    }// end of toHTMLFormat
    
    
    //Make every word from result into clickable spannableString
    private void toSpannableString () {
    text = tv.getText();
    if (text instanceof Spannable) {
    Spannable sp = (Spannable) tv.getText();
    //Toast.makeText(this, sp, Toast.LENGTH_LONG).show();
    URLSpan[] urlspan = sp.getSpans(0, text.length(), URLSpan.class);
    
    SpannableStringBuilder style = new SpannableStringBuilder(text);
    style.clearSpans();
    for (URLSpan url : urlspan) {
    MyClickableURLSpan mClickUrlSpan = new MyClickableURLSpan(url.getURL());
    style.setSpan(mClickUrlSpan, sp.getSpanStart(url), sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    tv.setText(style);
    }
    }
    
    
    private static class MyClickableURLSpan extends ClickableSpan {

    private String mUrl;
    
    public MyClickableURLSpan(String url) {
// TODO Auto-generated constructor stub
    mUrl = url;
}
    
@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
//Remove any punctuation sign of a word on right hand side, e.g. "," , "!", or "."
String temp = "";
if (mUrl.startsWith("(") || mUrl.startsWith("[")) {
temp = mUrl.substring(1, mUrl.length());
mUrl = temp;
}
if (mUrl.endsWith(")") || mUrl.endsWith("]") ) {
temp = mUrl.substring(0, mUrl.length()-1);
mUrl = temp;
}
if (mUrl.startsWith("\"") || mUrl.startsWith("'")) {
temp = mUrl.substring(1, mUrl.length());
mUrl = temp;
}
if (mUrl.endsWith("\"") || mUrl.endsWith("'")) {
temp = mUrl.substring(0, mUrl.length()-1);
mUrl = temp;
}
if (mUrl.endsWith(".") || mUrl.endsWith(",") || mUrl.endsWith("!")) {
temp = mUrl.substring(0, mUrl.length()-1);
mUrl = temp;
}
wv.loadUrl("http://lingvo.yandex.ru/" + mUrl + "/по-английски/");
}

@Override
public void updateDrawState(TextPaint ds) {
// TODO Auto-generated method stub
//super.updateDrawState(ds);
ds.setColor(ds.linkColor);
ds.setUnderlineText(false);
}
    
    }//end of class
}


*************************
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:textColor="#00FF00"
        android:textSize="16dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="2dp"
        android:text="英文新聞"></TextView>
    
        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

       
<!-- 

android:layout_marginTop="10dp"
 -->
        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
             />
        
        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#FFF380"
            android:fadingEdge="vertical"
            android:paddingTop="10dip"
            android:scrollbars="vertical" >

            <TextView
                android:id="@+id/textview01"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="4dp"
                android:text="@string/hello" >
            </TextView>
        </ScrollView>
        
    </LinearLayout>

***********************
Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cq.spannable.read.english.text"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/read"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".Cq_SpannableReadEngActivity"
            android:screenOrientation="landscape" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Spannable String 的變化


Spannable String 的變化

public class Cq_SpannableStringActivity extends Activity {
    /** Called when the activity is first created. */
TextView mtv = null;
SpannableString msp = null;
String source = "字體測試字體大小一半兩倍前景色背景色正常粗體斜體粗斜體下畫線刪除線x1x2電話郵件網站斷信採信地圖X軸綜合/bot";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mtv = (TextView) findViewById(R.id.textview);
        
        //Create a SpannableString obj
        msp = new SpannableString(source);
        
        //Set font (default, default-bold, monospace, serif, san-serif)
        msp.setSpan(new TypefaceSpan("monospace"), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new TypefaceSpan("serif"), 2, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        //Set font Size (絕對值,單位:像素)
        msp.setSpan(new AbsoluteSizeSpan(20), 4, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new AbsoluteSizeSpan(20, true), 6, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //dip true: 表示字體大小單位為dip,否則就是像素,同上
        
      //Set font Size (相對值,單位:像素) 參數表示為默認字體大小的倍數
        msp.setSpan(new RelativeSizeSpan(0.5f), 8, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new RelativeSizeSpan(2.5f), 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        //Set foreground color
        msp.setSpan(new ForegroundColorSpan(Color.MAGENTA), 12, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
      //Set Background color
        msp.setSpan(new BackgroundColorSpan(Color.CYAN), 15, 18, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        //Set fontstyle:regular, bold, italic, bold-italic
        msp.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 18, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 20, 22, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 22, 24, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 24, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        //Set underline, strikethrough, subscript, superscript
        msp.setSpan(new UnderlineSpan(), 27, 30, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan (new StrikethroughSpan(), 30, 33, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan (new SubscriptSpan(), 34, 35, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan (new SuperscriptSpan(), 36, 37, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        //Links (setMovementMethod  should be added)
        msp.setSpan(new URLSpan("tel:0229205319"), 37, 39, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new URLSpan("mailto:cqchoucq@gmail.com"), 39, 41, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new URLSpan("http://tw.yahoo.com"), 41, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new URLSpan("sms:0229205319"), 43, 45, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new URLSpan("mms:0229205319"), 45, 47, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new URLSpan("geo:38.899533, -77.036476"), 47, 49, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        //Set fontSize (相對值,單位:像素)參數表示為默認字體寬度的多少倍
        msp.setSpan(new ScaleXSpan(2.0f), 49, 51, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //2.0f 為寬度的兩倍,即x軸方向放大默認字體的兩倍,而高度不變
        
        
        //Set font (including font name, style, color, linking color)
        ColorStateList csllink = null;
        ColorStateList csl = null;
        
        XmlResourceParser xppcolor = getResources().getXml(R.color.color);
        try {
        csl = ColorStateList.createFromXml(getResources(), xppcolor);
        }catch(XmlPullParserException e) {
        e.printStackTrace();
        }catch(IOException e) {
        e.printStackTrace();
        }
        
        XmlResourceParser xpplinkcolor = getResources().getXml(R.color.linkcolor);
        try {
        csllink = ColorStateList.createFromXml(getResources(), xpplinkcolor);
        }catch(XmlPullParserException e) {
        e.printStackTrace();
        }catch(IOException e) {
        e.printStackTrace();
        }
        
        msp.setSpan(new TextAppearanceSpan("monospace", android.graphics.Typeface.BOLD_ITALIC, 30, csl, csllink), 51, 53, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        
        //Set list item symbol
        msp.setSpan (new BulletSpan(android.text.style.BulletSpan.STANDARD_GAP_WIDTH, Color.GREEN), 0, msp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //第一個參數表示symbol的寬度,第二個參數表示symbol的顏色
        
        //setPicture
        Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        msp.setSpan(new ImageSpan(drawable), 53, 57, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        mtv.setText(msp);
        mtv.setMovementMethod(LinkMovementMethod.getInstance());
        
    }
}

android -- ImageView


Matrix - 放大和縮小

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

private int bmpWidth;
private int bmpHeight;

private Bitmap bitmap;
//private LinearLayout linearLayout;
private ImageView mImageView;
private Button btnSmall;
private Button btnReset;
private Button btnLarge;
private float scale;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
     
        mImageView = (ImageView)findViewById(R.id.imageView1);
        btnLarge = (Button)findViewById(R.id.btnEnlarge);
        btnReset = (Button)findViewById(R.id.reset);
        btnSmall = (Button)findViewById(R.id.btnShrink);
     
        //透過  BitmapFactory.decodeResource 取得 bitmap
        bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.yih911030_01_300);
     
        //取得寬高
        bmpWidth = bitmap.getWidth();
        bmpHeight = bitmap.getHeight();
     
        scale = 1;
     
        loadImage();
     
      //設定放大按鈕監聽器
       btnLarge.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
scale *= 1.3;
loadImage();
}
   
       });
     
 
     //設定原來大小監聽器
        btnReset.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
scale = 1;
loadImage();
}
});
     
        //設定縮小按鈕監聽器
        btnSmall.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
scale *= 0.7;
loadImage();

}
});
     
    }
 
    private void loadImage(){
   
    android.graphics.Matrix matrix = new android.graphics.Matrix();
    matrix.postScale(scale, scale);
   
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
    mImageView.setImageBitmap(resizedBitmap);
   
    }


}




***********************************
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:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="*** 圖示放大縮小 ***"
        android:layout_gravity="center" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" >

        <Button
            android:id="@+id/btnEnlarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="21sp"
            android:text="放大" />

        <Button
            android:id="@+id/reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="17sp"
            android:text="原尺寸" />

        <Button
            android:id="@+id/btnShrink"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            android:text="縮小"
             />

    </LinearLayout>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:layout_gravity="center"
         />

</LinearLayout>

2012年8月17日 星期五

voice_recognition: (2)



manifest.xml:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cq.voice.recognition02"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/voice2"
        android:label="VoiceR2"
         >
        <activity
            android:label="@string/app_name"
            android:name=".Cq_VoiceRecognition02Activity"
             android:configChanges="orientation">
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ItemDemoPage"
            android:configChanges="orientation"></activity>
    </application>

</manifest>


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

main.java:


public class Cq_VoiceRecognition02Activity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */

ListView listview;
static final int check = 111;
protected static final boolean String = false;
private String [] stringData = {"fish","restaurant","car","menu"};

private TextView resultTextView;


OnClickListener transBtnListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voice_recognition);
     
        listview = (ListView)findViewById(R.id.listView1);
        Button b = (Button)findViewById(R.id.bVoice);
        b.setOnClickListener(this);
     
     
    }//end of onCreate

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Intent intent = new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "不要害羞,請張口說話!");
startActivityForResult(intent, check);
}//end of onClick




@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub

if (requestCode == check && resultCode == RESULT_OK) {
ArrayList<String> results = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));

// 檢查一共幾筆資料
listview.setClickable(true);
Toast.makeText(
Cq_VoiceRecognition02Activity.this,
"一共查詢到 "
+ Integer
.toString(listview.getAdapter().getCount())
+ " 個項目", Toast.LENGTH_LONG).show();

// // 檢查與我們的資料庫是否有吻合的項目
// int inqueredItemCount = listview.getAdapter().getCount();
// int index = 0;
// for (int i = 0; i < inqueredItemCount; i++) {
//
// String item = (String) listview.getAdapter().getItem(i);
// Toast.makeText(this, item, Toast.LENGTH_SHORT).show();
//
// for (int j = 0; j < stringData.length; j++) {
//
// Toast.makeText(this, "stringData = " + stringData[j], Toast.LENGTH_SHORT).show();
// if (item == stringData[j]) {
// index++;
// Toast.makeText(this, "找到相符合的資料!", Toast.LENGTH_SHORT).show();
//
// }else {
// Toast.makeText(this, i + " 筆不是!", Toast.LENGTH_SHORT).show();
// }
// }
// }
//
//
// if (index == 0){
// Toast.makeText(this, "沒有資料!", Toast.LENGTH_SHORT).show();
// }else {
// Toast.makeText(this, "一共 " + index + " 筆", Toast.LENGTH_SHORT).show();
// }

// 設定點選的項目
listview.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {

// 取得Clicked String
String item = (String) listview.getAdapter().getItem(
position);

// 利用TOAST顯示點選的項目
Toast.makeText(Cq_VoiceRecognition02Activity.this,
Integer.toString(position), Toast.LENGTH_SHORT)
.show();
Toast.makeText(Cq_VoiceRecognition02Activity.this,
"您選了 \"" + item + "\"", Toast.LENGTH_SHORT).show();

resultTextView = (TextView)findViewById(R.id.resultTV);
resultTextView.setText("選擇的字句: " + item);


// test for ItemDemoPage
Intent intent = new Intent(Cq_VoiceRecognition02Activity.this, ItemDemoPage.class);
intent.putExtra("TEXT", item);
startActivity(intent);


}
});

}


super.onActivityResult(requestCode, resultCode, data);
}//end of OnActivityResult

 
}//end of Cq_VoiceRecognition02Activity



*************************************************
ItemDemoPage.java:


public class ItemDemoPage extends Activity{

public static final String ENCODING = "UTF-8";
String fileName = "speech_rec01.txt";
String message = "";

TextView tv;
Button editBtn;
Button doneBtn;
Button clearBtn;
Button playBtn;
EditText  et;

TextToSpeech tts;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.item_demo_play);

tv = (TextView) findViewById(R.id.clickedText);

editBtn = (Button)findViewById(R.id.editBtn);
doneBtn = (Button)findViewById(R.id.doneBtn);
clearBtn = (Button)findViewById(R.id.clearBtn);
playBtn = (Button) findViewById(R.id.playBtn);
et = (EditText)findViewById(R.id.editText1);

//tts = new TextToSpeech(getApplicationContext(), this);

 //自共同記憶區取得傳遞資料,變數名稱:TEXT
 Bundle extras = getIntent().getExtras();
 if (extras != null){
//   tv.setText(extras.getString("TEXT"));

//  String previousText = readFileData (fileName);
//  String secondPart = extras.getString("TEXT");
//  message = previousText + secondPart;

 String comma = ","; //句子間的分野
 message = extras.getString("TEXT") + comma;
 writeFileData(fileName, message);
 String result = readFileData (fileName);
 tv.setText(result);

 }

 //修改內容
 editBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
et.setText(tv.getText().toString());
}
});

 //完成
 doneBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
deleteFile(fileName);
String message = et.getText().toString();
writeFileData(fileName, message);

//完成時將keyboard 隱藏,以不至於檔到螢幕的View
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(et.getWindowToken(), 0);

String result = readFileData(fileName);
tv.setText(result);

et.setText("");

}
});


 //Clear all data
 clearBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
deleteFile(fileName);
tv.setText("(沒有資料,請回到前一頁!!!)");
et.setText("");
}
});


}// end of onCreate()


//寫入指定的資料
public void writeFileData (String fileName, String message) {
try {
FileOutputStream fos = openFileOutput(fileName, MODE_APPEND);
byte [] bytes = message.getBytes(); //將要寫入的字串轉換為byte陣列
fos.write(bytes); //將byte陣列寫入檔案
fos.close(); //關閉FileOutputStream物件
} catch (Exception e) {
e.printStackTrace();
}
} // end of writeFileData


public String readFileData (String fileName) {
String result = "";
try {
FileInputStream fis = openFileInput(fileName);
int length = fis.available();//獲取檔案長度
byte [] buffer = new byte[length];//新建byte陣列用於讀入資料
fis.read(buffer);//將檔案內容讀入到byte陣列中
result = EncodingUtils.getString(buffer, ENCODING);//將byte陣列轉換成指定格式的字串
fis.close();//關閉檔案輸入串流
} catch (Exception e) {
e.printStackTrace();
}
return result;//返回讀到的資料字串
}
}


***************************************************
不需要:
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="@string/hello" />

</LinearLayout>

***************************************************
res/layout/item_demo_play.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="vertical"
    android:background="@drawable/cloud01" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

    </EditText>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/editBtn"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="5dp"
            android:text="修改" />

        <Button
            android:id="@+id/doneBtn"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="5dp"
            android:text="完成" />
        
        <Button
            android:id="@+id/clearBtn"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="5dp"
            android:text="清除" />

    </LinearLayout>

    <TextView
        android:id="@+id/clickedText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:background="#987766"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:paddingLeft="5dp"
        android:textSize = "25dp"
        android:textColor = "#FFFFFF"
        android:gravity="center" />

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/playBtn"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:text="播放" />

    </LinearLayout>

</LinearLayout>

******************************************************
res/layout/voice_recognition.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="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="4dip"
        android:text="按下按鈕,開始說話!!!" />

    <Button
        android:id="@+id/bVoice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="speakButtonClicked"
        android:text="按  我!" />
    <TextView
        android:id="@+id/resultTV"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="4dip"
        android:background="#987766"
        android:text="選擇的字句 :"
        android:textSize = "18dp" />
  
    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:layout_marginTop="5dp" >
    </ListView>
    

</LinearLayout>

VideoView



影片

public class Cq_VideoViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        VideoView videoview = (VideoView)findViewById(R.id.videoView1);
        videoview.setVideoPath("/sdcard/external_sd/GirlWePursued.m4v");
        MediaController mc = new MediaController(this);
        videoview.setMediaController(mc);
        videoview.requestFocus();
        videoview.start();
    }
}

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


<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/TableLayout01"
    android:gravity="center" >

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</TableLayout>


TextToSpeech




public final class Cq_TextToSpeechActivity extends Activity implements OnInitListener,OnClickListener, android.view.View.OnClickListener{
    /** Called when the activity is first created. */
private TextToSpeech tts;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tts = new TextToSpeech(getApplicationContext(), this);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(this);
    }

 
  //關閉
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
tts.shutdown();
}



//開始
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS){
tts.speak("I'm ready!", TextToSpeech.QUEUE_FLUSH, null);
}else{
System.out.println("Oops!");
}
}

//處理TextToSpeech
public void onClick(final View v) {
// TODO Auto-generated method stub
TextView TextView01 = (TextView)findViewById(R.id.editText1);
tts.speak(TextView01.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}


@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView TextView01 = (TextView)findViewById(R.id.editText1);
tts.speak(TextView01.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
}

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

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

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Talk" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="top"
        android:text="I love Ta ta because she is cute, gorgeous, charming and intelligent. If you don't believe me, you may dial 0961234567. And ask for Ta ta Chen. You're going to love her.
        The following message is brought by CQ Corporation.">
     

    </EditText>

</LinearLayout>

ListActivity & ExpandableListView



ListActivity (Multiple Choice + Single Choice + Header/Footer)

Multiple Choice:




public class Cq_MyListActivityMultipleChoice extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        
        String [] values1 = new String []{"蘋果", "香吉士", "奇異果", "西洋梨", "西瓜", "哈密瓜", "葡萄", "杏子", "琵琶", "甘蔗", "龍眼", "荔枝", "橘子", "榴槤", "火龍果", "柚子", "小紅苺", "紅毛丹", "柿子", "楊桃"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, values1); 
        setListAdapter(adapter);
        
        ListView listview = getListView();
        listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
    }
}


********************************************
Single-Choice:


public class Cq_MyListActivitySingleChoice extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        
        String [] values1 = new String []{"蘋果""香吉士""奇異果""西洋梨""西瓜""哈密瓜""葡萄""杏子""琵琶""甘蔗""龍眼""荔枝""橘子""榴槤""火龍果""柚子""小紅苺""紅毛丹""柿子""楊桃"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, values1); 
        setListAdapter(adapter);
        
        ListView listview = getListView();
        listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        
    }
}


*******************************************
FOOTER & HEADER:




//Footer and Header A
        ListView listview = getListView();
        View header = getLayoutInflater().inflate(R.layout.header, null);
        View footer = getLayoutInflater().inflate(R.layout.footer, null);



TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
textview1.setText(getEvent + " :   ");
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview2.setText(Integer.toString(str1.length) + " events");


        listview.addHeaderView(header);
        listview.addFooterView(footer);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, android.R.id.text1, values1);
        listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        setListAdapter(adapter);



************************************************
//Footer and Header B
如果用的是 ExpandableListActivity




//Set Header
        ListView listview = getExpandableListView();
        View header = getLayoutInflater().inflate(R.layout.mainheader, null);
        ImageView iconimg = (ImageView)header.findViewById(R.id.iconImage);
        TextView headertv1 = (TextView)header.findViewById(R.id.headerTextView01);
        TextView headertv2 = (TextView)header.findViewById(R.id.headerTextView02);
        iconimg.setImageResource(R.drawable.airplane1);
       
        headertv1.setText("旅遊英語實用會話");
        headertv2.setText("English Phrasal Books for Tourists");
        listview.addHeaderView(header);
        
        //Set Adapter
        mAdapter = new MyExpandableListAdapter(this);
        setListAdapter(mAdapter);
        

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

//example 2: Create a customized Header in a ListView under ListActivity      

ListView listview = getListView();
View header = getLayoutInflater().inflate(R.layout.header, null);

//取得 headerlayout.xml 裡的物件
TextView textview1 = (TextView)header.findViewById(R.id.headerTextView01);
TextView textview2 = (TextView)header.findViewById(R.id.headerTextView02);
textview1.setText(getEvent + " :   ");
textview2.setText(Integer.toString(str1.length) + " events");

listview.addHeaderView(header);

ArrayAdapter<String> adapter = new EventAdapter(this, str1, str2);
setListAdapter(adapter);

*************
附上:Customized    headerlayout.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="wrap_content"
     >

          <TextView
            android:id="@+id/headerTextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="5px"
            android:layout_marginRight="10px"
            android:layout_marginTop="1px"
            android:text="運動" 
            android:textSize = "20dp"
            android:textColor="@color/lime"/>

        <TextView
            android:id="@+id/headerTextView02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="1px"
            android:layout_marginRight="2px"
            android:layout_marginTop="1px"
            android:layout_toRightOf="@+id/headerTextView01"
            android:text="項目"
            android:textSize = "20dp"
            android:textColor="@color/lime"/>


</RelativeLayout>