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)
用於定義顯示Toast的Activity,文本和時間
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());
//通過id將ImageView設置為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.
NOTE:nested 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=數值//在LinearLayout,weight成反比,其他的成正比
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需要占据3个column,则可以通过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/layoutfolder中layoutXML的时候,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){
//獲取inflater,inflater是把Layout轉化為View
LayoutInflaterinflater = mContext.getLayoutInflater();
//View android.view.LayoutInflater.inflate(int resource, ViewGroup root,boolean attachToRoot)
//獲取包含ImageView和TextView的layout並轉化為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)ProgressBar,TimerTask
//定義水平進度條,否則為圓形進度條
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.ImageSwitcher,Gallery
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 : 一个可以有0到3个按钮,一个单选框或复选框的列表的对话框.警告对话框可以创建大多数的交互界面,是推荐的类型.
*进度对话框 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_dialog為xml文件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+F2或PgDn,某些机型会被设计为右软键(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
更多相关文章
- android仿iPhone滚轮控件实现及源码
- Android 在弹出Dialog(带EditText)的同时弹出软键盘并且EditText中
- Android中的webView控件实现网页缩放
- Android 设置Edittext获取焦点并弹出软键盘
- Android:EditText 软键盘退出监听解决方法
- Android精准的获取底部虚拟键盘的高度
- Android 设置对话框中的确定按钮的 enabled 属性
- Android 自定义控件实现点击波浪效果(九)
- 第八篇 TabHost控件