您的位置:首页 > 移动开发 > Android开发

Android笔记---- Android应用界面开发(3)

2015-01-04 17:50 288 查看
进度条(ProgressBar)的功能和用法

拖动条(SeekBar)的功能和用法

星级评分条(RatingBar)的功能和用法

选项卡(TabHost)的功能和用法

列表视图(ListView)

网格视图(GridView)和图像切换器(ImageSwicher)

拖动效果(Gallery)

对话框(Dialog)的功能和用法

菜单(Menu)的功能和用法

进度条(ProgressBar)的功能和用法

进度条(ProgressBar)是一种非常实用的组件,通常用于向用户显示某个耗时操作完成的进度。

Android系统提供了两大类进度条样式,第一类包括长形进度条(progessBarStyleHorizontal)和圆形进度条(progress-BarStyleLarge)。进度条的用处很多,比如,应用程序装载资源和网络连接时,可以提示用户稍等,这一类进度条只是代表应用程序某一部分程序的执行情况,而整个应用程序执行情况,则可以通过应用程序标题栏来显示一个进度条,可以调用Activity的requestWindowFeature()方法。

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="任务完成的进度" />
<!-- 定义一个水平进度条 -->

<ProgressBar
android:id="@+id/bar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100" />
<!-- 定义一个水平进度条,并改变轨道外观 -->

<ProgressBar
android:id="@+id/bar2"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progressDrawable="@drawable/my_bar" />

</LinearLayout>


ProgressBarTest.java

public class ProgressBarTest extends Activity
{
//该程序模拟填充长度为100的数组
private int[] data = new int[100];
int hasData = 0;
//记录ProgressBar的完成进度
int status = 0;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ProgressBar bar = (ProgressBar) findViewById(R.id.bar);
final ProgressBar bar2 = (ProgressBar) findViewById(R.id.bar2);
//创建一个负责更新的进度的Handler
final Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
//表明消息是由该程序发送的。
if (msg.what == 0x111)
{
bar.setProgress(status);
bar2.setProgress(status);
}
}
};
//启动线程来执行任务
new Thread()
{
public void run()
{
while (status < 100)
{
// 获取耗时操作的完成百分比
status = doWork();
// 发送消息到Handler
Message m = new Message();
m.what = 0x111;
// 发送消息
mHandler.sendMessage(m);
}
}
}.start();
}
//模拟一个耗时的操作。
public int doWork()
{
//为数组元素赋值
data[hasData++] = (int)(Math.random() * 100);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return hasData;
}
}


拖动条(SeekBar)的功能和用法

拖动条(SeekBar)通过滑块的位置来标识数值—而且拖动时允许用户拖动滑块来改变值,因此拖动条通常用于对系统的某种数值进行调节,比如音量调节等。

SeekBar允许用户改变拖动条的滑块外观,改变滑块的外观通过如下属性来指定。

android:thumb:指定一下Drawable对象,该对象将作为自定义滑块。

为了让程序响应拖动条滑块位置的改变,程序可以考虑为它绑定一个OnSeekBarChangeListener监听器。

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

<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="240px"
android:src="@drawable/lijiang" />
<!-- 定义一个拖动条,并改变它的滑块外观 -->

<SeekBar
android:id="@+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="255"
android:thumb="@drawable/icon" />

</LinearLayout>


SeekBarTest.java

public class SeekBarTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView image = (ImageView)findViewById(R.id.image);
SeekBar seekBar = (SeekBar)findViewById(R.id.seekbar);

seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
//当拖动条的滑块位置发生改变时触发该方法
@Override
public void onProgressChanged(SeekBar arg0
, int progress, boolean fromUser)
{
//动态改变图片的透明度
image.setAlpha(progress);

}
@Override
public void onStartTrackingTouch(SeekBar bar){}
@Override
public void onStopTrackingTouch(SeekBar bar){}
});
}
}


星级评分条(RatingBar)的功能和用法

星级评分条(RatingBar)和拖动条有相同的父类,即AbsSeekBar,和拖动条用法和功能都十分接近,它们都允许用户通过拖动来改变进度。二者最大的区别是:RatingBar通过星星来表示进度。

星级评分条所支持的常见的XML属性:

android:isIndicator 评分条是否允许用户改变

android: numStars 设置星级评分条共有多少个星级

android: rating 设置该星级评分条默认的星级

android: stepSize 设置每次最少需要多少个星级

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

<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="240px"
android:src="@drawable/lijiang" />
<!-- 定义一个星级评分条 -->

<RatingBar
android:id="@+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:max="255"
android:numStars="5"
android:progress="255"
android:stepSize="0.5" />

</LinearLayout>


RatingBarTest.java

public class RatingBarTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView image = (ImageView)findViewById(R.id.image);
RatingBar ratingBar = (RatingBar)findViewById(R.id.rating);

ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener()
{
//当拖动条的滑块位置发生改变时触发该方法
@Override
public void onRatingChanged(RatingBar arg0
, float rating, boolean fromUser)
{
//动态改变图片的透明度,其中255是星级评分条的最大值,
//5个星星就代表最大值255
image.setAlpha((int)(rating * 255 / 5));
}
});
}
}


选项卡(TabHost)的功能和用法

选项卡(TabHost)是一种非常实用的组件,可以在窗口上放置多个标签页,每个标签页相当于获得了一个与外部容器相同大小的组件摆放区域。可以放置多个组件。

通过以下两个方法来创建选项卡、添加选项卡

newTabSpec(String tag):创建选项卡

addTab(TabHost.TabSpec tabSpec):添加选项卡

使用TabHost的步骤:

在界面布局中定义TabHost组件,并为该组件定义该选项卡内容。

Activity应继承TabActivity。

调用TabActivity的getTabHost()方法获取TabHost对象。

通过TabHost对象的方法来创建选项卡、添加选项卡。

Main.xml

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

<!-- 定义第一个标签页的内容 -->

<LinearLayout
android:id="@+id/tab01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="页卡1"
android:textSize="11pt" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="页卡1"
android:textSize="11pt" />
</LinearLayout>
<!-- 定义第二个标签页的内容 -->

<LinearLayout
android:id="@+id/tab02"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="页卡2"
android:textSize="11pt" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="页卡2"
android:textSize="11pt" />
</LinearLayout>
<!-- 定义第三个标签页的内容 -->

<LinearLayout
android:id="@+id/tab03"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:textSize="11pt" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="页卡3"
android:textSize="11pt" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="页卡3"
android:textSize="11pt" />
</LinearLayout>

</TabHost>


TabHostTest.java

public class TabHostTest extends TabActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TabHost tabHost = getTabHost();
//设置使用TabHost布局
LayoutInflater.from(this).inflate(R.layout.main,
tabHost.getTabContentView(), true);
//添加第一个标签页
tabHost.addTab(tabHost.newTabSpec("tab1")
.setIndicator("页卡1标题")
.setContent(R.id.tab01));
//添加第二个标签页
tabHost.addTab(tabHost.newTabSpec("tab2")
//在标签标题上放置图标
.setIndicator("页卡2标题"
, getResources().getDrawable(R.drawable.icon))
.setContent(R.id.tab02));
//添加第三个标签页
tabHost.addTab(tabHost.newTabSpec("tab3")
.setIndicator("页卡3标题")
.setContent(R.id.tab03));
}
}


列表视图(ListView)

列表视图(ListView)是一种非常广泛的一种组件,以垂直列表的形式显示所有列表项。

创建ListView的两种方法:

直接使用ListView进行创建。

让Activity继承ListActivity

ListView常用的XML属性如下:

android: choiceMode 设置ListView的选择行为

android:divider 设置ListView列表项的分隔条(可用颜色/Drawable)

android:dividerHeight 设置分隔条的高度

android:entries 指定数组资源,将根据数组资源生成ListView

android:footerDividersEnabled 若为false,不在foot View前绘分隔条

android:headerDividersEnabled 若为false,不在header View前绘分隔条

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0000ff"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
</LinearLayout>


ListActivityTest.java

public class ListActivityTest extends ListActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//		//设置使用自己的界面布局
//		setContentView(R.layout.main);
String[] arr = { "item1", "time2", "item3" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, arr);
// 设置该窗口显示列表
setListAdapter(adapter);
}
}


网格视图(GridView)和图像切换器(ImageSwicher)

网格视图(GridView)用于在界面上按行、列分布的方式来显示多个组件。

GridView和ListView有共同的父类:AbsListView,主要区别: ListView只是在一个方向分布;而GridView会在两个方向上分布。

GridView也需要通过Adapter来提供显示的数据:既可以通过SimpleAdapter来为GridView提供数据,也可通过开发B-aseAdapter的子类来为GridView提供数据。

GridView常用的XML属性如下所示:

android:columnWidth 指定列的宽度

android:gravity 设置对齐方式

android:horizontalSpacing 设置各元素之间的水平间距

android:numColumns 设置列数年

android:stretchMode 设置拉伸模式

android:verticalSpacing 设置各元素之间的垂直间距

图片切换器(ImageSwicher)由FrameLayout派生而来,来实现图片的切换。 ImageSwicher类必须通过设置一个ViewFactory,主要用来将显示的图片和父窗口区分开来,因些需要实现ImageSwicher.ViewFactory接口,通过makeView()方法来显示图片,该方法通过返回一个ImageView,而ImageSwicher则负责显示这个ImageView。

Cell.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:padding="5pt"
>
<ImageView
android:id="@+id/image1"
android:layout_width="50dp"
android:layout_height="50dp"
/>
</LinearLayout>


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:gravity="center_horizontal"
android:orientation="vertical" >

<!-- 定义一个GridView组件 -->

<GridView
android:id="@+id/grid01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:horizontalSpacing="pt"
android:numColumns="4"
android:verticalSpacing="2pt" />
<!-- 定义一个ImageSwitcher组件 -->

<ImageSwitcher
android:id="@+id/switcher"
android:layout_width="320dp"
android:layout_height="320dp"
android:layout_gravity="center_horizontal" />

</LinearLayout>


GridViewTest.java

public class GridViewTest extends Activity
{
private static final String TAG = "GridViewTest";
int[] imageIds = new int[]
{
R.drawable.img5 , R.drawable.img6 , R.drawable.img7
, R.drawable.img8 , R.drawable.img9 , R.drawable.img10
, R.drawable.img11 , R.drawable.img12	, R.drawable.img13
, R.drawable.img14 , R.drawable.img15 , R.drawable.img16
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//创建一个List对象,List对象的元素是Map
List<Map<String, Object>> listItems
= new ArrayList<Map<String, Object>>();
for (int i = 0; i < imageIds.length; i++)
{
Map<String, Object> listItem = new HashMap<String, Object>();
listItem.put("image" , imageIds[i]);
listItems.add(listItem);
}
//获取显示图片的ImageSwitcher
final ImageSwitcher switcher = (ImageSwitcher)
findViewById(R.id.switcher);
//设置图片更换的动画效果
switcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
//为ImageSwitcher设置图片切换的动画效果
switcher.setFactory(new ViewFactory()
{
@Override
public View makeView()
{
ImageView imageView = new ImageView(GridViewTest.this);
imageView.setBackgroundColor(0xff0000);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
return imageView;
}
});
//创建一个SimpleAdapter
SimpleAdapter simpleAdapter = new SimpleAdapter(this
, listItems
//使用/layout/cell.xml文件作为界面布局
, R.layout.cell
, new String[]{"image"}
, new int[]{R.id.image1});
GridView grid = (GridView)findViewById(R.id.grid01);
//为GridView设置Adapter
grid.setAdapter(simpleAdapter);
//添加列表项被选中的监听器
grid.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position , long id)
{
//显示当前被选中的图片
switcher.setImageResource(imageIds[position % imageIds.length]);
}
@Override
public void onNothingSelected(AdapterView<?> parent){}
});
//添加列表项被单击的监听器
grid.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent
, View view, int position, long id)
{
//显示被单击的图片的图片
switcher.setImageResource(imageIds[position % imageIds.length]);
}
});
}
}


拖动效果(Gallery):画廊视图

画廊视图(Gallery)和Spinner两个组件有共同的父类:AbsSpinner,表明Gallery和Spinner都是一个列表框,二者的区别是: Spinner是一个垂直的列表选择框,供用户选择;而Gallery显示的是一个水平的列表选择框,允许用户通过拖动来查看上一个、下一个列表项。

Gallery额外提供的XML属性如下:

android:animationDuration 设置列表切换时的动画持续时间

android:gravity 设置对方方式

android:spacing 设置Gallery内列表项之间的间距

android:unselectedAlpha 设置没有选中的列表项的透明度

Gallery的用法也是要为它提供一个内容Adapter,该Adapter的getView方法所返回的View将作为Gallery列表的列表项;如果程序需要监听Gallery选择项的改变,可以通过给Gallery添加OnItemSelectedListener监听器来实现。

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

<!-- 定义一个ImageSwitcher组件 -->

<ImageSwitcher
android:id="@+id/switcher"
android:layout_width="320dp"
android:layout_height="320dp" />
<!-- 定义一个Gallery组件 -->

<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:spacing="3pt"
android:unselectedAlpha="0.6" />

</LinearLayout>


GallaryTest.java

public class GallaryTest extends Activity
{
int[] imageIds = new int[]
{
R.drawable.img01, R.drawable.img02,
R.drawable.img03, R.drawable.img04, R.drawable.img05,
R.drawable.img06, R.drawable.img07, R.drawable.img08,
R.drawable.img09, R.drawable.img10, R.drawable.img11,
R.drawable.img12 };

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Gallery gallery = (Gallery) findViewById(R.id.gallery);
// 获取显示图片的ImageSwitcher对象
final ImageSwitcher switcher = (ImageSwitcher)
findViewById(R.id.switcher);
// 为ImageSwitcher对象设置ViewFactory对象
switcher.setFactory(new ViewFactory()
{
@Override
public View makeView()
{
ImageView imageView = new ImageView(GallaryTest.this);
imageView.setBackgroundColor(0xff0000);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
return imageView;
}
});
// 设置图片更换的动画效果
switcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
// 创建一个BaseAdapter对象,该对象负责提供Gallery所显示的图片
BaseAdapter adapter = new BaseAdapter()
{
@Override
public int getCount()
{
return imageIds.length;
}
@Override
public Object getItem(int position)
{
return position;
}
@Override
public long getItemId(int position)
{
return position;
}

// 该方法的返回的View就是代表了每个列表项
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
// 创建一个ImageView
ImageView imageView = new ImageView(GallaryTest.this);
imageView
.setImageResource(imageIds[position % imageIds.length]);
// 设置ImageView的缩放类型
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(75, 100));
TypedArray typedArray = obtainStyledAttributes(
R.styleable.Gallery);
imageView.setBackgroundResource(typedArray.getResourceId(
R.styleable.Gallery_android_galleryItemBackground, 0));
return imageView;
}
};
gallery.setAdapter(adapter);
gallery.setOnItemSelectedListener(new OnItemSelectedListener()
{
// 当Gallery选中项发生改变时触发该方法
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id)
{
switcher.setImageResource(imageIds[position % imageIds.length]);
}

@Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
}
}


对话框(Dialog)的功能和用法

Android提供了丰富的对话框支持,如下4种对话框:

AlertDialog:功能丰富,实际应用最广泛的对话框。

ProgressDialog:进度对话框,对简单进度条的封装

DatePickerDialog:日期选择对话框,对DatePicker的包装

TimePickerDialog:时间选择对话框,对TimePicker的包装

以上4种对话框功能最强大、用法最灵活的就是AlertDialog。

使用AlertDialog创建对话框大致步骤如下:

创建AlertDialog.Builder对象,该对象是AlertDialog的创建器

调用AlertDialog.Builder的方法为对话框设置图标、标题、内容等

调用AlertDialog.Builder的create()方法创建AlertDialog对话框

调用AlertDialog的show()方法显示对话框。

DatePickerDialog和TimePickerDialog功能简单,用法如下:

通过new关键字创建DatePickerDialog和TimePickerDialog实例,调用它们的show()方法即可将日期选择对话框、时间选择对话框显示出来。

为DatePickerDialog和TimePickerDialog绑定事件监听器,这样可以保证用户通过DatePickerDialog、TimePickerDialog设置事件时触发监听器,从而通过监听器来获取用户设置的事件。

ProgressDialog代表了进度对话框,程序只要创建ProgressDialog实例,并将它们显示出来就是一个进度对话框。

ProgressDialog包含了以下常用方法。

setIndeterminate(boolean indeterminage) 设置对话框里的进度条里的进度条不显示进度值。

setMax(int max) 设置对话框里进度条的最大值

setMessage(CharSequence message) 设置对话框里显示信息

setProgress(int value) 设置进度条里的进度值

setProgressStyle(int style) 设置对话框里进度条的风格

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:gravity="center_horizontal"
android:orientation="vertical" >

<!-- 显示一个普通的文本编辑框组件 -->

<EditText
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false" />
<!-- 定义一个普通的按钮组件 -->

<Button
android:id="@+id/bn01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示对话框" />

</LinearLayout>


DialogTest.java

public class DialogTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bn = (Button)findViewById(R.id.bn01);
//定义一个AlertDialog.Builder对象
final Builder builder = new AlertDialog.Builder(this);
//为按钮绑定事件监听器
bn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View source)
{
// 设置对话框的图标
builder.setIcon(R.drawable.tools);
// 设置对话框的标题
builder.setTitle("自定义普通对话框");
// 设置对话框显示的内容
builder.setMessage("对话框提示内容体");
// 为对话框设置一个“确定”按钮
builder.setPositiveButton("确定"
//为列表项的单击事件设置监听器
, new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
EditText show = (EditText) findViewById(R.id.show);
// 设置EditText内容
show.setText("用户单击了“确定”按钮!");
}
});
// 为对话框设置一个“取消”按钮
builder.setNegativeButton("取消"
,  new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
EditText show = (EditText) findViewById(R.id.show);
// 设置EditText内容
show.setText("用户单击了“取消”按钮!");
}
});
//创建、并显示对话框
builder.create().show();
}
});
}
}


菜单(Menu)的功能和用法

Android手机用一个按钮“Menu”专门来显示菜单,与桌面应用的菜单不同,Android应用中的期间条默认是看不见的,只有当用户单击手机上的“Menu”键,系统才会显示该应用关联的菜单。

Menu接口中只是一个父接口,该接口下有两个子接口。

SubMenu:它代表一个子菜单,它可以包含1~N个MenuItem

ContextMenu:它代表一个上下文菜单。它可以包含1~N个MenuItem

上面的方法归纳起来就是两个:add()方法用于添加菜单项;addSubMenu()用于添加子菜单。区别在于是否将子菜单、菜单项添加到指定菜单组中,是否使用资源文件中的字符串资源来设置标题。

添加菜单或子菜单的步骤如下:

重写Activity的onCreateOptionsMenu(Menu menu)的方法,在该方法里调用Menu对象的方法来添加菜单或子菜单。

如果要响应菜单事件,重写Activity的onOptionsItemSelected(MenuItem mi)方法即可。

创建复选菜单项和单选菜单项

如果想要创建菜单是单选菜单项或多选菜单项,可以调用MenuItem的如下方法:

setCheckable(boolean checkable):设置该菜单项是否可以被勾选。调用该方法后的菜单项默认是多选菜单。

setGroupCheckable(int group,boolean checkable,boolean exclusive) 设置group组里的所有菜单项是否可勾选;如果将exclusive设为true,那么它们将是一组单选菜单项。

setAlphabeticShortcut(char alphaChar)设置字母快捷键

setNumericShortcut(char numericChar)设置数字快捷键

setShortcut(char numericChar,char alphaChar) 设置两种快捷键

上下文菜单(ContextMenu)

Android用ContextMenu来代表上下文菜单,为Android应用开发上下文菜单与开发选项菜单的方法基本相似,因为ContextMenu继承了Menu,因此程序可用相同的方法为它添加菜单项。

开发上下文菜单的步骤如下:

重写Activity的onCreateContextMenu(ContextMenu menu,View source,ContextMenu.ContextMenuInfo menuInfo)方法。

调用Activity的registerForContextMenu(View view)方法为view组件注册上下文菜单。

如果要为菜单项提供响应,可以考虑重写onContextItemSelected (MenuItem mi)方法,或为指定菜单项绑定事件监听器。

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15pt"
android:text="可通过上下文菜单修改背景色"
/>
</LinearLayout>


ContextMenuTest.java

public class ContextMenuTest extends Activity
{
// 为每个菜单定义一个标识
final int MENU1 = 0x111;
final int MENU2 = 0x112;
final int MENU3 = 0x113;
private TextView txt;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
// 为文本框注册上下文菜单
registerForContextMenu(txt);
}

// 每次创建上下文菜单时都会触发该方法
@Override
public void onCreateContextMenu(ContextMenu menu, View source,
ContextMenu.ContextMenuInfo menuInfo)
{
menu.add(0, MENU1, 0, "红色");
menu.add(0, MENU2, 0, "绿色");
menu.add(0, MENU3, 0, "蓝色");
// 将三个菜单项设为单选菜单项
menu.setGroupCheckable(0, true, true);
//设置上下文菜单的标题、图标
menu.setHeaderIcon(R.drawable.tools);
menu.setHeaderTitle("选择背景色");
}

// 菜单项被单击时触发该方法。
@Override
public boolean onContextItemSelected(MenuItem mi)
{
switch (mi.getItemId())
{
case MENU1:
mi.setChecked(true);
txt.setBackgroundColor(Color.RED);
break;
case MENU2:
mi.setChecked(true);
txt.setBackgroundColor(Color.GREEN);
break;
case MENU3:
mi.setChecked(true);
txt.setBackgroundColor(Color.BLUE);
break;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: