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