Android學習筆記整理 2011.02.15 1

Android學習筆記整理 2011.02.15

 

1.獲取控件方法

View android.app.Activity.findViewById(int id)

示例:

Buttonbutton = (Button)findViewById(R.id.linear_layout);

 

2.設置當前Activity顯示的Layout

voidandroid.app.Activity.setContentView(int layoutResID)

示例:

setContentView(R.layout.main);

//顯示標題類型

booleanandroid.app.Activity.requestWindowFeature(int featureId)

 

3.設置控件點擊監聽事件和鍵盤事件

點擊事件

方法1

button.setOnClickListener(button_click);

privateOnClickListener button_click = new OnClickListener()

{

 

@Override

publicvoid onClick(View v)

{

//dosomething

}

};//注意分號

 

方法2:

定義 publicclass 類名 extends Activityimplements OnClickListener

只要實現

@Override

publicvoid onClick(View v)

{

//dosomething

}

即可。

 

鍵盤事件

edittext.setOnKeyListener(newOnKeyListener()

{

@Override

publicboolean onKey(View v, int keyCode, KeyEvent event)

{

if(event.getAction()== KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER)

{

//按下了Enter鍵,處理事件

}

 

}

});

 

 

4.Intent跳轉

1)一般跳轉

Intentintent = new Intent();

intent.setClass(AndroidStudyLayout.this,android.study_layout.LinearRelativeLayout.class);

startActivity(intent);

 

(2)跳轉+傳遞值

在(1)的基礎上加入:

Bundlebundle = new Bundle();

bundle.putString("key","abc");

intent.putExtras(bundle);

 

獲取傳遞的值

Bundlebundle = getIntent().getExtras();

Stringstr =bundle.getString("key");

 

(3)使用請求碼和返回碼

將(1)的startActivity(intent);改為startActivityForResult(intent,0);

方法:voidandroid.app.Activity.startActivityForResult(Intent intent, intrequestCode)

然後在當前的Activity中定義:

protectedvoid onActivityResult(int requestCode, int resultCode,Intent data)

{

if(resultCode == 100)

{

Bundlebundle = data.getExtras();

Stringtext = "";

text=bundle.getString("key");

editText.setText(text);

}

}

跳轉的Activity在調用finish()前應當使用方法

voidandroid.app.Activity.setResult(int resultCode, Intent data)

setResult(100,intent);

 

5.使用風格

這樣可以避免在xml文件中寫入大量重複數據

定義風格:

<?xmlversion="1.0" encoding="utf-8"?>

<resources>

<stylename="style_bar">

<itemname="android:textStyle">italic</item>

<itemname="android:textColor">#00FF00</item>

<itemname="android:textSize">30px</item>

</style>

<!--可以定義多個style-->

</resources>

 

使用風格:

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="水平進度條"

style="@style/style_bar"

/>

 

6.Toast

用於消息提示,Toast會自動消失

1)基本的Toast方法

Toast android.widget.Toast.makeText(Context context, CharSequence text,int duration)

用於定義顯示ToastActivity,文本和時間

voidandroid.widget.Toast.setGravity(int gravity, int xOffset, intyOffset)

設定Toast顯示位置和偏移該位置的向量(x,y)

voidandroid.widget.Toast.show()

定義忘了不要忘記調用此方法顯示Toast

 

(2)自定義Toast

首先調用(1)中前2個方法定義Toast,設置顯示的文本和時間,show()之前加入:

//View android.widget.Toast.getView(),獲取Toast佈局

LinearLayouttoastView = (LinearLayout) toast.getView();

//定義一個ImageView

ImageViewimageCodeProject = new ImageView(getApplicationContext());

//通過idImageView設置為drawable文件夾中圖片

imageCodeProject.setImageResource(R.drawable.android_pressed);

//Latout中加入ImageView,voidandroid.view.ViewGroup.addView(View child, int index)

toastView.addView(imageCodeProject,1); //加入的ImageView索引為1,即圖片在文字下方。

//最後show()

 

7.佈局

(1)線性佈局LinearLayout

在一行單獨組織界面元素,可以通過屬性android:orientation設置水平組織方式界面元素android:orientation="horizontal"

設置垂直方式組織界面元素android:orientation="vertical"

可以嵌套使用LinearLayout,也就是在一個LinearLayout中使用另一個LinearLayout.

NOTEnested layout並不侷限於一種形式的layout。比如可以把LinearLayout嵌套在Framelayout 裏。

常用參數

android:orientation="vertical"/“horizontal"

android:layout_width="fill_parent"/"wrap_content"

android:layout_height="fill_parent"/"wrap_content"

android:layout_weight=數值//LinearLayoutweight成反比,其他的成正比

android:padding= 數值dip //控件間距

 

2)相對佈局RelativeLayout

這是一個相對來說複雜的佈局方式。

每個界面元素都是相對於其他元素的位置來佈局。

常用控件參數

android:layout_toRightOf="@id/控件id"//在控件右方

android:layout_below="@id/控件id"//在控件下方

android:layout_marginLeft="25dip"//具左邊25dip

 

3)表格佈局TableLayout

只需在XML裏定義row,android自動調整column

如果一個row需要佔據3column,則可以通過android:layout_span=3來設置。

默認情況下:

如果一個元素需要放在一個row裏,要放到哪裏呢?android默認把它放在這個row的第一個沒有被佔用的column

如果想特定地把一個元素放在一個column,那麼需要用ndroid:layout_column 來設置。

<TableLayout

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:layout_weight="2">

<TableRow>

...

</TableRow>

</TableLayout>

 

 

(4)Framelayout

每一行顯示一個圖標。如果兩個圖標在一起的話,圖標會overlap.當圖標之間發生overlap的時候,就會以overlap的形式佈局。

FrameLayout有這樣一個用處:就是界面元素若需要通過程序控制其可見性,可以使用FrameLayout.

使用 android:visibility屬性,它有三個值

visible- 顯示;

invisible-不可見,但是依然佔據位置;

gone -不可見,並不佔據位置;

 

(5)AlternateLayout

LinearLayout中,如果在一行放了太多的界面元素,那麼很可能發生在一行顯示空間不夠,界面元素髮生重疊現象。

這種問題,往往和屏幕大小,和屏幕的現實方向有關係。

比如,在水平方向顯示沒有問題,但是在垂直方式顯示會有overlap.

那麼解決這個問題的方式就是AlternateLayout

在讀取res/layoutfolderlayoutXML的時候,android首先會在查看一下三種佈局

res/layout-land– The alternate layout for a landscape UI

res/layout-port– The alternate layout for a portrait UI

 

 

8.ListView

(1)定義一般的ListView

ListViewlistview = new ListView(this);

/*定義適配器,ArrayAdapter<CharSequence> android.widget.ArrayAdapter.createFromResource(Context context, inttextArrayResId, int textViewResId)*/

finalArrayAdapter<CharSequence> adapter =ArrayAdapter.createFromResource

(Listview_01.this,R.array.list_01,android.R.layout.simple_list_item_1); //android.R.layout.simple_list_item_1 為系統定義的常量

//添加適配器

listview.setAdapter(adapter);

 

array.list_01.xml:

<?xmlversion="1.0" encoding="utf-8"?>

<resources>

<string-arrayname="list_01">

<item>張三</item>

<item>李四</item>

<item>王五</item>

<item>朱六</item>

</string-array>

</resources>

 

(2)定義自定義的ListView

listView= (ListView)findViewById(android.R.id.list); //調用系統的listid.

/*定義適配器,自定義方法FileArrayAdapter(Activity context, int resource, int textViewResourceId, List<FileInfo> objects)

mContents是一個文件信息類FileInfo對象*/

ListAdapteradapter = newFileArrayAdapter(this,R.layout.file_item_view,R.id.file_name,mContents);

this.setListAdapter(adapter);

 

publicclass FileArrayAdapter extends ArrayAdapter<FileInfo>{

privateActivity mContext = null;

publicFileArrayAdapter(Activity context, int resource,

inttextViewResourceId, List<FileInfo> objects) {

super(context,resource, textViewResourceId, objects);

this.mContext= context;

}

@Override

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

//獲取inflaterinflater是把Layout轉化為View

LayoutInflaterinflater = mContext.getLayoutInflater();

//View android.view.LayoutInflater.inflate(int resource, ViewGroup root,boolean attachToRoot)

//獲取包含ImageViewTextViewlayout並轉化為View

ViewitemView = inflater.inflate(R.layout.file_item_view, null,false);

ImageViewimageView = (ImageView)itemView.findViewById(R.id.file_icon);

TextViewtextView = (TextView)itemView.findViewById(R.id.file_name);

FileInfofileInfo = this.getItem(position);

//設置圖片

if(fileInfo.isFolder())

imageView.setImageResource(R.drawable.folder);

else

imageView.setImageResource(R.drawable.file);

//設置文本

textView.setText(fileInfo.getName());

return(itemView);

}

}

 

9.下拉列表Spinner

1)調用xml中的string-array

Spinner spinner_1 = (Spinner)findViewById(R.id.spinner_1);

/*ArrayAdapter<CharSequence> android.widget.ArrayAdapter.createFromResource(Context context, inttextArrayResId, int textViewResId)*/

ArrayAdapter<CharSequence> adapter =ArrayAdapter.createFromResource(

SpinnerActivity.this,R.array.words,android.R.layout.simple_spinner_item);

//設置列表資源類型為系統常量android.R.layout.simple_spinner_dropdown_item

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner_1.setAdapter(adapter);

 

array.xml

<?xmlversion="1.0" encoding="utf-8"?>

<resources>

<string-arrayname="words">

<item>say</item>

<item>see</item>

<item>seek</item>

<item>send</item>

<item>setup</item>

<item>super</item>

</string-array>

</resources>

 

2)在code中定義列表選項

privatefinal String[] myword = {"tab","tag","the","theme","tim","tom"};

 

Spinnerspinner_2 = (Spinner)findViewById(R.id.spinner_2);

ArrayList<String> array_list = new ArrayList<String>();

for(int i = 0;i < myword.length;i++)

{

array_list.add(myword[i]);

}

/*android.widget.ArrayAdapter.ArrayAdapter(Context context, int textViewResourceId, List<String> objects))*/

ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,

android.R.layout.simple_spinner_item,array_list);

//設置列表資源類型為系統常量android.R.layout.simple_spinner_dropdown_item

adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner_2.setAdapter(adapter2);

 

10.AntoCompleteTextView

AutoCompleteTextView textview = (AutoCompleteTextView )findViewById(

R.id.auto_complete_text);

ArrayAdapter<CharSequence> adapter3 =ArrayAdapter.createFromResource(

SpinnerActivity.this,R.array.mywords,android.R.layout.simple_spinner_item);

textview.setAdapter(adapter3);

 

11.SeekBar,ProgressBar,TimerTask

(1)SeekBar

seekbar= (SeekBar)findViewById(R.id.seekbar_horizontal);

seekbar_textview= (TextView)findViewById(R.id.seekbar_text);

seekbar.setOnSeekBarChangeListener(newOnSeekBarChangeListener()

{

@Override

publicvoid onProgressChanged(SeekBar seekBar, int progress,booleanfromUser)

{

seekbar_textview.setText("拖動條被移動了"+ seekbar.getProgress() + "%");

}

@Override

publicvoid onStartTrackingTouch(SeekBar seekBar)

{

;

}

@Override

publicvoid onStopTrackingTouch(SeekBar seekBar)

{

;

}

});

 

(2)ProgressBarTimerTask

//定義水平進度條,否則為圓形進度條

progress= (ProgressBar)findViewById(R.id.progress_horizontal);

textview= (TextView)findViewById(R.id.progress_text);

IncrementTasktask = new IncrementTask(textview);

//使用線程來動態進度條的顯示文本

timer= new Timer();

/*voidjava.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, longperiod)參數為:執行的任務,第一次要等多久後開始執行,

循環執行的間隔時間*/

timer.scheduleAtFixedRate(task,0, 1000);

 

//重寫TimerTask

classIncrementTask extends TimerTask

{

WeakReference<TextView> mRef;

Handler handler = new Handler();

public IncrementTask(TextView text)

{

mRef = new WeakReference<TextView>(text);

}

public void run()

{

handler.post(new Runnable()

{

public void run()

{

if(progress.getProgress() < 70)

progress.setProgress(progress.getProgress() + 5);

else if(progress.getProgress() >= 70 &&progress.getProgress() < 100)

progress.setProgress(progress.getProgress() + 3);

else

{

timer.cancel();

mRef.get().setText("任務結束!");

return;

}

mRef.get().setText("當前任務進度為 "+ progress.getProgress() + "%");

}

});

}

}

 

12.ImageSwitcherGallery

publicclass ImageSwitcherGallery extends Activity implements

OnItemSelectedListener,ViewFactory {

privateImageSwitcher image_switcher;

privateGallery gallery;

 

//定義圖片id的整型數組

privateInteger[] mThumbIds = { R.drawable.a1, R.drawable.a2,

R.drawable.a3,R.drawable.a4, R.drawable.a5,

};

 

privateInteger[] mImageIds = { R.drawable.a1, R.drawable.a2,

R.drawable.a3, R.drawable.a4, R.drawable.a5, };

 

@Override

protectedvoid onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.image_switcher_gallery);

 

image_switcher= (ImageSwitcher) findViewById(R.id.switcher);

//voidandroid.widget.ViewSwitcher.setFactory(ViewFactory factory)視圖切換工廠,需實現makeView()

image_switcher.setFactory(this);

//定義選擇圖片時的動畫

image_switcher.setInAnimation(AnimationUtils.loadAnimation(this,

android.R.anim.fade_in));

image_switcher.setOutAnimation(AnimationUtils.loadAnimation(this,

android.R.anim.fade_out));

gallery= (Gallery) findViewById(R.id.gallery);

gallery.setAdapter(newImageAdapter(this));

gallery.setOnItemSelectedListener(this);

}

 

/*View android.study_layout.ImageSwitcherGallery.makeView()-- abstract*/

@Override

publicView makeView() {

ImageViewimage = new ImageView(this);

image.setBackgroundColor(0xFF000000);

image.setScaleType(ImageView.ScaleType.FIT_CENTER);

//設置顯示的格式

image.setLayoutParams(newImageSwitcher.LayoutParams(

LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

returnimage;

}

 

publicclass ImageAdapter extends BaseAdapter {

privateContext mContext;

publicImageAdapter(Context c) {

mContext= c;

}

 

publicint getCount() {

returnmThumbIds.length;

}

 

publicObject getItem(int position) {

returnposition;

}

 

publiclong getItemId(int position) {

returnposition;

}

 

/*View android.study_layout.ImageSwitcherGallery.ImageAdapter.getView(intposition, View convertView, ViewGroup parent)*/

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

ImageViewimage = new ImageView(mContext)

image.setImageResource(mThumbIds[position]);

image.setAdjustViewBounds(true);

image.setLayoutParams(newGallery.LayoutParams(

LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

returnimage;

}

 

}

 

@Override

publicvoid onItemSelected(AdapterView<?> parent, View view, intposition,

longid) {

//獲取ImageSwitcher

ImageSwitcherimage_switcher = (ImageSwitcher) findViewById(R.id.switcher);

//設置要顯示的圖片

image_switcher.setImageResource(mImageIds[position]);

 

}

 

@Override

publicvoid onNothingSelected(AdapterView<?> parent) {

}

}

 

13.TabActivity

TabHosttabhost = getTabHost();

//voidandroid.widget.TabHost.addTab(TabSpec tabSpec)

//TabSpec android.widget.TabHost.TabSpec.setIndicator(CharSequence label)

//TabSpec android.widget.TabHost.TabSpec.setContent(int viewId)

LayoutInflater.from(this).inflate(R.layout.tab,tabhost.getTabContentView(),true);

tabhost.addTab(tabhost.newTabSpec("tab1").setIndicator("標籤1").setContent(R.id.tab_text1));

tabhost.addTab(tabhost.newTabSpec("tab2").setIndicator("標籤2").setContent(R.id.tab_text2));

tabhost.addTab(tabhost.newTabSpec("tab3").setIndicator("標籤3").setContent(R.id.tab_text3));

 

14.Dialog

一個對話框一般是一個出現在當前Activity之上的一個小窗口.處於下面的Activity失去焦點,對話框接受所有的用戶交互.對話框一般用於提示信息和與當前應用程序直接相關的小功能.

AndroidAPI 支持下列類型的對話框對象:

*警告對話框 AlertDialog : 一個可以有03個按鈕,一個單選框或複選框的列表的對話框.警告對話框可以創建大多數的交互界面,是推薦的類型.

*進度對話框 ProgressDialog: 顯示一個進度環或者一個進度條.由於它是 AlertDialog 的擴展,所以它也支持按鈕

 

創建對話框

protected Dialog onCreateDialog ( int id ) {

Dialogdialog ;

switch( id ) {

caseDIALOG_PAUSED_ID :

//do the work to define the pause Dialog

break;

caseDIALOG_GAMEOVER_ID :

//do the work to define the game over Dialog

break;

default:

dialog= null ;

}

returndialog ;

}

調用對話框

show(DIALOG_PAUSED_ID);

 

(1)AlertDialog

publicDialog exitDialog(){

AlertDialog.Builderbuilder = new AlertDialog.Builder(mContext);

builder.setTitle(TITLE_EXIT);

builder.setMessage(MESSAGE_EXIT_SAVE_REMIND);

builder.setPositiveButton(BUTTON_NAME_EXIT_AND_SAVE,new DialogInterface.OnClickListener() {

@Override

publicvoid onClick(DialogInterface dialog, int which){

}

});

builder.setNeutralButton(BUTTON_NAME_EXIT, new DialogInterface.OnClickListener(){

@Override

publicvoid onClick(DialogInterface dialog, int which) {

}

});

builder.setNegativeButton(BUTTON_NAME_CANCEL,new DialogInterface.OnClickListener(){

@Override

publicvoid onClick(DialogInterface dialog, int which) {

//關閉對話框

alert.dismiss();

}

});

alert= builder.create();

returnalert;

}

 

 

(2)自定義Dialog

publicDialog createNewFolderDialog(){

dialog = new CDialog(mContext);

dialog.setContentView(R.layout.create_folder_dialog);

dialog.setTitle(TITLE_CREATE_NEW_FOLDER);

TextViewtexttext = (TextView) dialog.findViewById(R.id.create_folder_text);

texttext.setText(MESSAGE_CREATE_NEW_FOLDER);

newFolderEditText= (EditText) dialog.findViewById(R.id.create_folder_edittext);

newFolderButton[0]= (Button) dialog.findViewById(R.id.create_folder_ok);

newFolderButton[1]= (Button) dialog.findViewById(R.id.create_folder_cancel);

returndialog;

}

 

R.layout.create_folder_dialogxml文件id

 

15.Menu

//創建一個menu

@Override

publicboolean onCreateOptionsMenu(Menu menu)

{

MenuInflaterinflater = getMenuInflater();

inflater.inflate(R.menu.option_menu,menu);

//按下Home鍵顯示

returnsuper.onCreateOptionsMenu(menu);

}

//相應事件

@Override

publicboolean onOptionsItemSelected(MenuItem item)

{

//dosomething

}

 

16.Android模擬器對應快捷鍵

Home鍵(小房子鍵)

在鍵盤上映射的就是home鍵,這倒是很好記。

 

Menu

用於打開菜單的按鍵,在鍵盤上映射的是F2鍵,PgUp鍵同樣可以。

 

Start

這個鍵在模擬器和G1真機上我都沒有找到到底是哪個鍵。映射的是Shift+F2PgDn,某些機型會被設計爲右軟鍵(rightsoftkey)

 

Back

返回鍵,用戶返回上一個UI或者退出當前程序。鍵盤上映射ESC鍵。

 

Call/Dial鍵(電話鍵)

接聽來電或啓動撥號面板,這是一部手機最基本的功能鍵。PC鍵盤映射爲F3鍵。

 

Hangup/LightOff鍵(掛機鍵)

掛斷電話或關閉背燈用。鍵盤映射F4鍵。

 

Search

在提供了Search功能的應用裏快速打開Search對話框,比如在Browser裏可以快速打開地址搜索欄。鍵盤映射F5

 

PowerDown鍵(關閉電源)

對應模擬器左上邊緣的電源按鈕,不過似乎在模擬器上按這個鍵並沒什麼用處。鍵盤映射F7

 

VolumeUp (增大音量)

鍵盤映射Ctrl+F5,也可以使用小數字鍵盤的”+”鍵。

 

VolumeDown(減小音量)

鍵盤映射Ctrl+F6,也可以使用小數字鍵盤的”-”鍵。

 

Camera

鍵盤映射Ctrl+F3。不過也許是我設置有問題,在模擬上用這個快捷鍵似乎沒任何反應。

 

SwitchScreen Orientation (旋屏)

旋轉模擬器屏幕方向,鍵盤映射Ctrl+F11。這是非常有用和常用的快捷鍵,幾乎所有應用都會受到屏幕方向帶來的Layout變化困擾,在開發程序時候,一定要測試屏幕方向的兼容性。

 

CellNetworking On/Off (手機網絡開關)

這裏說的手機網絡指的是GPRS/3G這種數據網絡,並不影響GSM網絡。對於編寫基於網絡應用的同學,這個快捷鍵非常有用,可以測試網絡異常中斷的情況。鍵盤映射F8

 

FullscreenMode (全屏模式)

一個沒什麼用的雞肋功能。也許對於測試畫面比較精細的遊戲能有點幫助。快捷鍵是大家喜聞樂見的Alt+Enter

 

Trackballmode (軌跡球模式)

這是一個非常有用的功能,按F6之後,可以打開軌跡球模式,模擬器左上角會顯示一個小軌跡球。通過鼠標移動,可以模擬軌跡球的轉動。對於測試利用軌跡球操作的應用會非常方便。

 

Trackballmode Temporaily (臨時軌跡球模式)

這個功能很有意思,如果你有比較短暫的使用軌跡球的操作,那麼可以按住Delete鍵滑動鼠標。釋放Delete鍵會自動結束軌跡球模式。

 

四方向鍵和中心鍵

對應鍵盤四方向鍵和Enter鍵,當然也可以用數字小鍵盤,KEYPAD_5對應中心鍵。

 

17.adb命令

adbpush <local> <remote> - copy file/dir to device

adbpull <remote> [<local>] - copy file/dir from device

adbshell - run remote shell interactively

adbshell <command> - run remote shell command

adbemu <command> - run emulator console command

adblogcat [ <filter-spec> ] - View device log

adbinstall [-l] [-r] [-s] <file> - push this package file to thedevice and install it

('-l'means forward-lock the app)

('-r'means reinstall the app, keeping its data)

('-s'means install on SD card instead of internal storage)

adbuninstall [-k] <package> - remove this app package from thedevice

('-k'means keep the data and cache directories)

adbstart-server - ensure that there is a server running

adbkill-server - kill the server if it is running

adbdevices -restart device

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章