第十三章dnf元素pk加点点

《C与指针》第十三章练习 - _monster - 博客园
13.1类型无关的链表查找
#include &stdio.h&
#include "node.h"
Node *search_list(Node *node, void const *value,
int (*compare)(void const *, void const *))
while(node != NULL){
if(compare(&node-&value, value) == return n /= if(quotient != char **ptr =
如果变量ptr加上1,它的效果是怎样的?
answer:As with all pointer arithmetic,the value one is scaled to the size of whatever the pointer is pointing at,which in this case is a pointer to a character,the result is that ptr is advanced to point at the next element of the array.
(和所有的算术指针一样,它是可以指向任何大小的标量的指针,在这个情况下它指向一个字符,所以结果就是ptr指向数组中的下一个元素)
3.假定你将要编写一个函数,它的起始部分如下所示:
void func(int ***arg){
参数类型是什么?画一张图,显示这个变量的正确用法,如果想取得这个参数所指代的整数,你应该使用怎样的表达式?
(这是一个指向指针的指针的指针,表达式***arg可以获得这个参数指向的整数)
4.下面的代码可以如果进行改进?
Transaction *
trans-&product-&orders += ** insert the filenam
strcpy(pathname + &answer:If the filename exceeds(超过) 15 characters(this one does not),it will overflow the memory allocated to hold the string literal,If the initial value of the pathname is ever changed,you must remember to change the literal constant ten also,but the real problem is that it overwrites the string literal,the effects of which are not defined by the Standard,The solusion is to declare pathname as an array,not a pointer.
(如果文件名超过15个字符,为了保存这个字符串会使内存溢出,如果pathname的初始值被改过,你必须记得改变字面值常量10,不过在实际问题中,字符串经常被更改,其影响是标准未定义的,这个解决办法应该声明pathname为一个数组,而不是一个指针)
9.下面的代码段有什么错误(如果有的话)?你如何修正它?
char pathname[] = "/usr/temp/";
** append the filenam
strcat(pathname, "abcde");
answer:The array is only as large as needed to hold its initial value,so appending anything to it overflows the memory array,probably overwriting some other variables,The solution is to make the array enough larger than the initail value to hold the longest filename that will be appended to it later,A potential(可能的) problem if this pathname prefix(前缀) is suppoised to be used with several different filenames,appending the next one with strcat will not produce the desired result.
(这个数组的大小只能容纳初始值,所以在后面添加任何东西都会使数组内存溢出,可能会覆盖其他变量,这个解决办法要使数组足够大可以包含最长的文件名,一个可能存在问题的地方是strcat,如果这个文件名前缀允许使用若干不同的文件名,在后面连接一个字符串可能不会产生预期的效果)
10.下面的代码段有什么错误(如果有的话)?你如何修正它?
char pathname[ ** append the filenam
strcat(pathname, filename);
answer:If the string in filename is longer than nine characters,it will overflow the array,if the length of a pathname has an upper bound,the array should be declared at least that large.Otherwise,the length of the filename can be computed and used to obtain memeory dynamically.
(如果filename中的字符长度比九还长,将会溢出数组,如果pathname的长度有一个上界,数组至少需要声明这个长度,否则,如果filename的长度能被计算可以使用动态内存获取)
11.标准表示如果对一个字符串常量进行修改,其效果是未定义的,如果你修改了字符串常量,有可能会出现什么问题呢?
answer:首先,有些编译器把字符串常量存放在无法进行修改的内存区域,如果你试图对这类字符串常量进行修改,就会导致程序终止,其次,即使一个字符串常量在程序中使用的地方不止一处,有些编译器只保存这个字符串常量的一份拷贝。修改其中一个字符串常量将影响程序中这个字符串常量出现的所有地方,这使得调试工作极为困难,例如,如果一开始执行了下面这条语句
strcpy("hello\n", "Bye!\n");
然后再执行下面这条语句:
printf("hello\n");
将打印出Bye!
1.编写一个程序,从标准输入中读取一些字符,并根据下面的分类计算各类字符所占的百分比:
不可打印字符
这些分类是根据ctype.h中的函数定义的,不能使用一系列的if语句。
#include &stdio.h&
#include &ctype.h&
#include &stdlib.h&
int unprint(int ch){
return !isprint(ch);
int (*test[])(int ch) = {
#define COUNT (sizeof(test) / sizeof(test[0]))
char *label[] = {
"control",
"whitespace",
"lower case",
"upper case",
"punctuation",
"unprintable"
int value[COUNT];
int main()
while((ch = getchar()) != EOF){
total += if(test[i](ch))
value[i]++;
if(total == for(i = value[i] * 2.编写一个通用目的的函数,遍历一个单链表,它应该接受两个参数,一个指向链表第一个节点的指针,和一个指向回调函数的指针,回调函数应该接受单个参数,也就是指向一个链表节点的指针,对于链表中的每个节点,都应该调用一次这个回调函数。这个函数需要知道链表节点的什么信息?
This function is probably not terribly useful,as it is nearly as easy to traverse the list on your own as it is to call a general purpose function to do it,On the other hand,the paradigm is valuable enough to justify this exercise.Note that the function still needs to know where the link is in the node structure,so it isn't all that general after all.
(这个函数可能不是特别有用,因为你自己调用一个通用目的函数来遍历这个链表几乎一样容易,另一方面,这个练习足以证明这个范式是有用的,注意这个函数仍然需要知道链表指向的节点的结构,所以它并不完全通用)
#include &stdio.h&
#inclue "node.h"
void sll_traversal(Node *root,void (*trav)(Node *))
while(root != NULL){
trav(root);
root = root-&
3.转换下列代码段,使它改用转移表而不是switch语句。
Transaction *
typedef enum {NEW, DELETE, FORWARD, BACKWORD,
SEARCH,EDIT} Trans_
switch(transaction-&type){
add_new_trans(list,transaction);
case DELETE:
current = delete_trans(list,transaction);
case FORWORD:
current = current-&
case BACKWORD:
current = current-&
case SEARCH:
current = search(list,transaction);
case EDIT:
edit(current,transaction);
printf("Illegal transaction type!\n");
&Several of the cases dothis code must be moved into functions,The main difficulty here is to comp up with a common prototype that will serve the needs of all of the necessary functions,it must contain each argument used by any function,the new functions must use the common prototype,and the existing function must be modified to match it,Most of the function will end up with at least one argument that they do not need,A pointer must be passed to current so that the appropriate funcitons can modify it.
(在不同的情况下执行不同的工作,这些代码必须移到函数中,主要的困难在于提出一个共同的原型来适应不同需要的函数,要包括任何一个函数使用的所有参数,新的函数都要使用这个共同的原型,已经存在的函数要转换来匹配新的原型,大多数函数至少有一个它们不需要的参数结尾,current必须通过指针来使函数修改它)&
void add_new_trans(Node *list, Node **current, Transaction *trans);
void delete_trans(Node *list, Node **current, Transaction *trans);
void search(Node *list, Node **current, Transaction *trans);
void edit(Node *list, Node **current, Transaction *trans);
void forword(Node *list, Node **current, Transaction *tran)
*current = (*current)-&
void backword(Node *list, Node **current, Transaction *tran)
*current = (*current)-&
void (*function[])(Node *, Node **, Transaction *) = {
add_new_trans,
delete_trans,
#define COUNT (sizeof(function) / sizeof(function[0]));
if(transaction-&type &= NEW && transaction &= EDIT)
function[transaction-&type](list, ¤t, transaction);
printf("Illegal transaction type!\n");
4.编写一个名叫sort的函数,它用于对一个任何类型的数组进行排序,为了使函数更为通用,他的其中一个参数必须是一个指向比较回调函数的指针,该回调函数由调用程序提供,比较函数接受两个参数,也就是两个指向需要进行比较的值的指针,如果两个值相等,返回0,如果第一个值小于第二个返回小于零的整数,否则,返回大于零的整数。sort函数的参数将是:
1.一个指向需要排序的数组的第一个值的指针
2.数组中值的个数
3.每个数组元素的长度
4.一个指向比较回调函数的指针
sort函数没有返回值。你将不能根据实际类型声明数组参数,因为函数应该可以对不同类型的数组进行排序,如果你把数据当成一个字符数组使用,你可以用第三个参数寻找实际数组中每个元素的起始位置,也可以用它交换两个数组元素(每次一个字节)。
对于简单的交换排序,你可以使用下面的算法,当然也可以使用你认为更好的算法。
&answer:This function is patterned after the qsort function provided in the ANSI C library,The only two tricks are locating the beginning of array element and interchanging two elements.The element length is used for both tasks.
(这个函数是模仿ANSI C库中提供的qsort函数,其中有两个小把戏,一个是传递数组首元素的位置,还有就是交换两个元素,两个函数中都使用了元素的长度)
5.编写代码处理命令行参数是十分乏味的,所以最好有一个标准函数来完成这项工作。但是不同的程序以不同的方式处理它们的参数,所以,这个函数必须非常灵活,以便使它能用于更多的程序。在本题中,你将编写这样一个函数。你的函数通过寻找和提取参数来提供灵活性。用户所提供的回调函数将执行实际的处理工作。下面是函数的原型。注意它的第四个参数和第五个参数是回调函数的原型。
char ** do_args(int argc, char **argv, char *control,
void (*do_arg)(int ch, char *value),
void (*illegal_arg)(int ch));
头两个参数就是main函数的参数,main函数对它们不做修改,直接传递给do_args,第三个参数是个字符串,用于标志程序期望接受的命令行参数。最后两个参数都是函数指针,它们是由用户提供的。do_args函数按照下面这样的方式处理命令行参数:
跳过程序名参数
while 下一次参数以一个横杆开头
  对于参数横杠后面的每个字符
    处理字符
返回一个指针,指向下一个参数指针
为了“处理字符”,你首先必须观察该字符是否位于control字符串内,如果它并不位于那里,调用illegal_arg指向函数,把这个字符作为参数传递过去。如果它位于control字符串内,但它的后面并不是跟一个+号,那么就调用do_arg所指向的函数,把这个字符和一个NULL指针作为参数传递过去。
如果该字符位于control字符串内并跟一个+号,那么就应该有一个值与这个字符相联系。如果当前参数还有其他字符,它们就是我们需要的值。否则,下一个参数才是这个值。在任何一种情况下,你应该调用do_arg所指向的函数,把这个字符和指向这个值的指针传递过去。如果不存在这个值(当前参数没有其他字符,且后面不再有参数),那么你应该调用Illegal_arg函数。注意:你必须保证这个值中的字符以后不会被处理。
当所有以一个横杆开头的参数被处理完毕后,你应该返回一个指向下一个命令行参数的指针的指针(也就是一个诸如&argv[4]或argv+4的值)。如果所有的命令行参数都以一个横杆开头,你就返回一个指向“命令行参数列表中结尾的NULL指针”的指针。
这个函数必须不能修改命令行参数指针,也不能修改参数本身,为了说明这一点,假定程序prog调用这个函数:下面的例子显示了几个不同集合的参数的执行结果。
#include &stdio.h&
#include &stdlib.h&
enum {NONE, FLAG, ARG};
argtype(register int ch, register int *control)
while(*control != '\0')
if(ch == *control++)
return *control == '+' ? ARG : FLAG;
return NONE;
char **do_args(int argc, char **argv, char *control,
void (*do_arg)(int ch, char *value),
void (*illegal_arg)(int ch))
register char *
register int
register int skip_
while((argp = *++argv) != NULL && *argp == '-'){
skip_arg = (*illegal_arg)(ch);
case NONE:
(*illegal_arg)(ch);
这可能是目前为止在这本书中学习最难的章节了,尤其是之前没有接触过回调函数、转接表和命令行参数,学习这一章可能会异常艰辛,所以要加油挺过这一关,可以多看几遍书,题目的话也要不停的阅读弄清楚意思了再动手,读不懂题目可能还是对内容不熟悉,另外这一章里的介绍的命令行参数的处理过程还是非常有用的,尤其对于喜欢用命令行的人和在Linux/Unix下工作的人,算是比较底层的东西。
阅读(...) 评论()1、ListView
在android开发中ListView是比较常用的组件,它以列表的形式展示具体内容,并且能够根据数据的长度自适应显示。抽空把对ListView的使用做了整理,并写了个小例子:
&列表的显示需要三个元素:
1.ListVeiw 用来展示列表的View。
2.适配器&用来把数据映射到ListView上的中介。
3.数据&&&&具体的将被映射的字符串,图片,或者基本组件。
根据列表的适配器类型,列表分为三种,ArrayAdapter,SimpleAdapter和SimpleCursorAdapter
其中以ArrayAdapter最为简单,只能展示一行字。SimpleAdapter有最好的扩充性,可以自定义出各种效果。SimpleCursorAdapter可以认为是SimpleAdapter对数据库的简单结合,可以方面的把数据库的内容以列表的形式展示出来。
&我们从最简单的ListView开始:
package com.example.
import java.util.ArrayL
import java.util.HashM
import java.util.L
import android.app.A
import android.app.ListA
import android.os.B
import android.view.M
import android.view.MenuI
import android.widget.ArrayA
import android.widget.ListV
import android.widget.SimpleA
public class AndroidControl2Activity extends Activity
private ListView listV
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_control2);
listView = new ListView(this);
listView.setAdapter(new ArrayAdapter&String&(this, android.R.layout.simple_expandable_list_item_1,getData()));
setContentView(listView);
private List&String& getData(){
List&String& data = new ArrayList&String&();
data.add("测试数据1");
data.add("测试数据2");
data.add("测试数据3");
data.add("测试数据4");
上面代码使用了(&context, int textViewResourceId,&&T& objects)来装配数据,要装配这些数据就需要一个连接ListView视图对象和数组数据的适配器来两者的适配工作,的构造需要三个参数,依次为this,布局文件(注意这里的布局文件描述的是列表的每一行的布局,android.R.layout.simple_list_item_1是系统定义好的布局文件只显示一行文字,数据源(一个List集合)。同时用setAdapter()完成适配的最后工作。运行后的显示效果如下图:
SimpleAdapter
simpleAdapter的扩展性最好,可以定义各种各样的布局出来,可以放上ImageView(图片),还可以放上Button(按钮),CheckBox(复选框)等等。下面的代码都直接继承了ListActivity,ListActivity和普通的Activity没有太大的差别,不同就是对显示ListView做了许多优化,方面显示而已。
下面的程序是实现一个带有图片的类表。
首先需要定义好一个用来显示每一个列内容的xml
&?xml version="1.0" encoding="utf-8"?&
&LinearLayout xmlns:android="/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent"&
&LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"&
&TextView android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:textSize="22px" /&
&TextView android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:textSize="13px" /&
&/LinearLayout&
&/LinearLayout&
实现代码:
package com.example.
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import android.app.A
import android.app.ListA
import android.os.B
import android.view.M
import android.view.MenuI
import android.widget.ArrayA
import android.widget.ListV
import android.widget.SimpleA
public class AndroidControl2Activity extends ListActivity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SimpleAdapter adapter = new SimpleAdapter(this,getData(),R.layout.activity_android_control2,
new String[]{"title","info"},
new int[]{R.id.title,});
setListAdapter(adapter);
private List&Map&String, Object&& getData() {
List&Map&String, Object&& list = new ArrayList&Map&String, Object&&();
Map&String, Object& map = new HashMap&String, Object&();
map.put("title", "G1");
map.put("info", "google 1");
list.add(map);
map = new HashMap&String, Object&();
map.put("title", "G2");
map.put("info", "google 2");
list.add(map);
map = new HashMap&String, Object&();
map.put("title", "G3");
map.put("info", "google 3");
list.add(map);
使用simpleAdapter的数据用一般都是HashMap构成的List,list的每一节对应ListView的每一行。HashMap的每个键值数据映射到布局文件中对应id的组件上。因为系统没有对应的布局文件可用,我们可以自己定义一个布局vlist.xml。下面做适配,new一个SimpleAdapter参数一次是:this,布局文件(xml),HashMap的 title 和 info。布局文件的组件id,title,info。布局文件的各组件分别映射到HashMap的各元素上,完成适配。
&2、Spinner
通常分5步:
第一步:添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项& 第二步:为下拉列表定义一个适配器,这里就用到里前面定义的list。 第三步:为适配器设置下拉列表下拉时的菜单样式。 第四步:将适配器添加到下拉列表上 第五步:为下拉列表设置各种事件的响应,这个事响应菜单被选中
&?xml version="1.0" encoding="utf-8"?&
&LinearLayout
android:id= "@+id/widget28"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent"
android:orientation= "vertical"
xmlns:android= "/apk/res/android" &
android:id= "@+id/TextView_Show"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:text= "你选择的是"
android:textSize= "25sp" &
&/TextView&
android:id= "@+id/spinner_City"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" &
&/Spinner&
&/LinearLayout&
package com.example.
import java.util.ArrayL
import java.util.L
import android.app.A
import android.os.B
import android.view.M
import android.view.MenuI
import android.view.V
import android.widget.AdapterV
import android.widget.AdapterView.OnItemSelectedL
import android.widget.ArrayA
import android.widget.S
import android.widget.TextV
public class AndroidControl3Activity extends Activity {
private List&String& list = new ArrayList&String&();
private Spinner myS
private TextView myTextV
private ArrayAdapter&String&
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_control3);
//Spinner显示
//第一步:添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项
list.add("北京");
list.add("上海");
list.add("深圳");
list.add("广州");
mySpinner = (Spinner)findViewById(R.id.spinner_City);
myTextView = (TextView)findViewById(R.id.TextView_Show);
//第二步:为下拉列表定义一个适配器,这里就用到里前面定义的list。
spinneradapter = new ArrayAdapter&String&(this,android.R.layout.simple_spinner_item, list);
//第三步:为适配器设置下拉列表下拉时的菜单样式。
spinneradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//第四步:将适配器添加到下拉列表上
mySpinner.setAdapter(spinneradapter);
//第五步:为下拉列表设置各种事件的响应,这个事响应菜单被选中
mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
public void onItemSelected(AdapterView&?& parent, View view,
int position, long id) {
// TODO Auto-generated method stub
myTextView.setText("您选择的是:"+ spinneradapter.getItem(position));
/* 将mySpinner 显示*/
view.setVisibility(View.VISIBLE);
public void onNothingSelected(AdapterView&?& parent) {
// TODO Auto-generated method stub
&&3、GridView
GirdView的一些属性:
android:numColumns="auto_fit" --------列数设置为自动 android:columnWidth="90dp",----------每列的宽度,也就是Item的宽度 android:stretchMode="columnWidth"------缩放与列宽大小同步 android:verticalSpacing="10dp"----------垂直边距 android:horizontalSpacing="10dp"-------水平边距
1、准备数据源
2、新建适配器
3、加载适配器
GridView(网格视图)是按照行列的方式来显示内容的,一般用于显示图片,图片等内容,比如实现九宫格图,用GridView是首选,也是最简单的,下面来个实例,
activity_android_control4.xml:
&?xml version="1.0" encoding="utf-8"?&
&LinearLayout xmlns:android="/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000"
android:id="@+id/gview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="auto_fit"
android:columnWidth="80dp"
android:stretchMode="columnWidth"
&&/GridView&
&/LinearLayout&
&?xml version="1.0" encoding="utf-8"?&
&LinearLayout xmlns:android="/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:padding="10dp"
&ImageView
android:src="@drawable/ic_launcher"
android:id="@+id/image"
android:layout_width="60dp"
android:layout_height="60dp"
android:id="@+id/text"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:text="文字"
&/LinearLayout&
AndroidControl4Activity.java:
package com.example.
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import android.app.A
import android.os.B
import android.view.M
import android.view.MenuI
import android.widget.GridV
import android.widget.SimpleA
public class AndroidControl4Activity extends Activity {
private GridV
private List&Map&String, Object&& data_
private SimpleAdapter sim_
// 图片封装为一个数组
private int[] icon = { R.drawable.address_book, R.drawable.calendar,
R.drawable.camera, R.drawable.clock, R.drawable.games_control,
R.drawable.messenger, R.drawable.ringtone, R.drawable.settings,
R.drawable.speech_balloon, R.drawable.weather, R.drawable.world,
R.drawable.youtube };
private String[] iconName = { "通讯录", "日历", "照相机", "时钟", "游戏", "短信", "铃声",
"设置", "语音", "天气", "浏览器", "视频" };
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_control4);
gview = (GridView) findViewById(R.id.gview);
//新建List
data_list = new ArrayList&Map&String, Object&&();
//获取数据
getData();
//新建适配器
String [] from ={"image","text"};
int [] to = {R.id.image,R.id.text};
sim_adapter = new SimpleAdapter(this, data_list, R.layout.item, from, to);
//配置适配器
gview.setAdapter(sim_adapter);
public List&Map&String, Object&& getData(){
//cion和iconName的长度是相同的,这里任选其一都可以
for(int i=0;i&icon.i++){
Map&String, Object& map = new HashMap&String, Object&();
map.put("image", icon[i]);
map.put("text", iconName[i]);
data_list.add(map);
return data_
&&4、Dialog
在Android开发中,我们经常会需要在界面上弹出一些对话框,比如询问用户或者让用户选择。这些功能我们叫它Android Dialog对话框,在我们使用Android的过程中,据我所知,Android Dialog的类型无非也就7种,下面我分别向大家介绍这7Android Dialog对话框的使用方法,希望对大家能有所帮助。
1、主窗体图1的实现,在Lanyout中添加7个按钮,代码如下所示:
1 &?xml version="1.0" encoding="utf-8"?&
2 &LinearLayout xmlns:android="/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" &
android:id="@+id/But_One"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="1" /&
android:id="@+id/But_Two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="2" /&
android:id="@+id/But_Three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="3" /&
android:id="@+id/But_Four"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="4" /&
android:id="@+id/But_Five"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="5" /&
android:id="@+id/But_Six"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="6" /&
android:id="@+id/But_Seven"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="7" /&
48 &/LinearLayout&
1 package ;
2 import android.app.A
3 import android.app.AlertD
4 import android.app.AlertDialog.B
5 import android.os.B
6 import android.view.V
7 import android.view.View.OnClickL
8 import android.widget.B
10 public class DialogActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
But_One=(Button) findViewById(R.id.But_One);
//注册按钮But_One
But_Two=(Button) findViewById(R.id.But_Two);
But_Three=(Button) findViewById(R.id.But_Three);
But_Four=(Button) findViewById(R.id.But_Four);
But_Five=(Button) findViewById(R.id.But_Five);
But_Six=(Button) findViewById(R.id.But_Six);
But_Seven=(Button) findViewById(R.id.But_Seven);
But_One.setOnClickListener(this);
//为按钮But_One注册侦听器
25 Button But_One,But_Two,But_Three,But_Four,But_Five,But_Six,But_S
//定义按钮
DialogActivity.java
2、图2的实现,设置单击&按钮1&时,弹出对话框,代码如下所示:
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.But_One)
AlertDialog.Builder builder=new AlertDialog.Builder(DialogActivity .this);//生成一个对话框对象
builder.setMessage("确定要退出吗?");
//设置对话框的显示信息
builder.setTitle("提示");
//设置对话框的标题
builder.setPositiveButton("确定",null);
//设置第一个按钮的Text,null处也可替换为new OnClickListener() {}
builder.setNegativeButton("取消",null);
//设置第二个按钮的Text
builder.create().show();
//创建并显示对话框
&3、图3的实现,设置单击&按钮2&时,弹出对话框,代码和效果图2如下所示:
if(v.getId()==R.id.But_Two)
AlertDialog.Builder builder= new AlertDialog.Builder(DialogActivity.this);//生成一个对话框对象
builder.setIcon( android.R.drawable.btn_star);//设置对话框的图标
builder.setTitle("喜好调查");
//设置对话的标题
builder.setMessage("你喜欢李连杰的电影吗");
//设置对话框的显示信息
builder.setPositiveButton("很喜欢",null);
builder.setNeutralButton("一般",null);
builder.setNegativeButton("不喜欢",null);
builder.create().show();
&4、图4的实现,设置单击&按钮3&时,弹出对话框,代码和效果图3如下所示:
1 if(v.getId()==R.id.But_Three)
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("请输入");
builder.setIcon(android.R.drawable.ic_dialog_info);
//设置对话框的图标
builder.setView(new EditText(this));
//设置对话框中显示一个输入框
builder.setPositiveButton("确定",null);
builder.setNegativeButton("取消",null);
builder.show();
&5、图5的实现,设置单击&按钮4&时,弹出对话框,代码和效果图4如下所示:
1 if(v.getId()==R.id.But_Four)
Builder builder=new AlertDialog.Builder(this);
//生成一个对话框对象
builder.setTitle("单选框");
//设置对话框的标题
builder.setIcon(android.R.drawable.ic_dialog_info);
//设置对话框的图标
builder.setSingleChoiceItems( new String[] { "Item1", "Item2" }, 0,null);
//设置对话框的单选项
builder.setNegativeButton("取消", null);
builder.create().show();
&6、图6的实现,设置单击&按钮5&时,弹出对话框,代码和效果图5如下所示:
1 if(v.getId()==R.id.But_Five)
Builder builder=new AlertDialog.Builder(this);
//生成一个对话框对象
builder.setTitle("复选框");
//设置对话框的标题
builder.setMultiChoiceItems( new String[] { "Item1", "Item2" }, null, null); //设置对话框的复选项
builder.setPositiveButton("确定", null); //设置对话框的第一个按钮"确定"
builder.setNegativeButton("取消", null); //设置对话框的第二个按钮"取消"
builder.show();
&7、图7的实现,设置单击&按钮6&时,弹出对话框,代码和效果图6如下所示:
1 if(v.getId()==R.id.But_Six)
Builder builder=new AlertDialog.Builder(this);
//生成一个对话框对象
builder.setTitle("列表框");
builder.setItems(new String[]{"Item1","Item2"},null);
builder.setNegativeButton("确定",null);
builder.create().show();
&8、图8的实现,设置单击&按钮7&时,弹出自定义对话框,这种对话框相对上面讲的要复杂一些,它需要通过一个.xml文件来传递你要呈现的布局。代码和效果图7如下所示:
1 &?xml version="1.0" encoding="utf-8"?&
2 &LinearLayout xmlns:android="/apk/res/android"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:background="#ffffffff" android:orientation="horizontal"
android:id="@+id/mydialog"&
&TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/tvname" android:text="姓名:" /&
&EditText android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/etname" android:minWidth="100dip"/&
12 &/LinearLayout&
dialog.xml
1 if(v.getId()==R.id.But_Seven)
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.mydialog,
new AlertDialog.Builder(this).setTitle("自定义布局").setView(layout)
.setPositiveButton("确定", null)
.setNegativeButton("取消", null).show();
DialogActivity.java
&&&&&学习了制作对话框,才发现其实对话框的制作也是非常简单的,一般情况下只需设置对话框的标题、信息、图标、按钮即可,有的时候还需要添加文本框、单选按钮、复选框、列表项。然而比较复杂的情况就是自定义对话框。在设置自定义对话框的时候,需要设计一个你的xml文件,里面是你的自定义布局,然后通过,主窗体调用xml来实现自定义对话框的制作。
&&5、ProgressDialog
先看效果:
布局文件:
&?xml version="1.0" encoding="utf-8"?&
&LinearLayout xmlns:android="/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"&
&Button android:text="圆形进度条" android:id="@+id/Button01"
android:layout_width="wrap_content" android:layout_height="wrap_content"&&/Button&
&Button android:text="长型进度条" android:id="@+id/Button02"
android:layout_width="wrap_content" android:layout_height="wrap_content"&&/Button&
&/LinearLayout&
package com.example.
import android.app.A
import android.app.ProgressD
import android.content.DialogI
import android.os.B
import android.view.M
import android.view.MenuI
import android.view.V
import android.view.View.OnClickL
import android.widget.B
public class ProgressDialogActivity extends Activity {
private ProgressDialog mpD
private Button btn1,btn2;
private int mCount = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_dialog);
//得到按钮对象
btn1 = (Button)findViewById(R.id.Button01);
btn2 = (Button)findViewById(R.id.Button02);
btn1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
mpDialog = new ProgressDialog(ProgressDialogActivity.this);
mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
mpDialog.setTitle("提示");//设置标题
mpDialog.setIcon(R.drawable.clock);//设置图标
mpDialog.setMessage("这是一个圆形进度条");
mpDialog.setIndeterminate(false);//设置进度条是否为不明确
mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消
mpDialog.setButton("确定", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
mpDialog.show();
//设置mButton02的事件***
btn2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
// TODO Auto-generated method stub
mCount = 0;
// 创建ProgressDialog对象
mpDialog = new ProgressDialog(ProgressDialogActivity.this);
// 设置进度条风格,风格为长形
mpDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 设置ProgressDialog 标题
mpDialog.setTitle("提示");
// 设置ProgressDialog 提示信息
mpDialog.setMessage("这是一个长形对话框进度条");
// 设置ProgressDialog 标题图标
mpDialog.setIcon(R.drawable.camera);
// 设置ProgressDialog 进度条进度
mpDialog.setProgress(100);
// 设置ProgressDialog 的进度条是否不明确
mpDialog.setIndeterminate(false);
// 设置ProgressDialog 是否可以按退回按键取消
mpDialog.setCancelable(true);
// 让ProgressDialog显示
mpDialog.show();
new Thread()
public void run()
while (mCount &= 100)
// 由线程来控制进度。
mpDialog.setProgress(mCount++);
Thread.sleep(100);
mpDialog.cancel();
catch (InterruptedException e)
mpDialog.cancel();
}.start();
&Android的菜单有三种:Options Menu   当用户按下menu button按钮时显示的菜单 Context Menu   当用户长久按住屏幕,即被注册显示上下文菜单的视图时显示的菜单 Submenu   当用户按下一个菜单的某个选项时弹出的子菜单
Options Menu创建选项菜单的步骤:
1、覆盖Activity 的onCreateOptionMenu(Menu menu)方法,当菜单第一次被打开时调用
2、调用Menu 的add( )方法添加菜单项(MenuItem),同时可以调用MenuItem 的setIcon( )方法来为菜单项设置图标
3、当菜单项(MenuItem)被选择时,覆盖Activity 的onOptionsItemSelected(MenuItem item)来响应事件
Context Menu顾名思义,与上下文(环境)有关。思想类似于Windows中的右键单击弹出的快捷菜单。操作时需要长时间按住某个东东不放。
创建上下文菜单的步骤:
1、覆盖Activity 的onCreateContextMenu(Menu menu)方法,调用Menu的add()方法添加菜单项(MenuItem)。
2、覆盖Activity 的onContextItemSelected(MenuItem iitem)来响应事件。
3、调用registerForContextMenu( )方法来为视图注册上下文菜单。
布局文件:
&RelativeLayout xmlns:android="/apk/res/android"
xmlns:tools="/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" &
android:id="@+id/ContextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="按我弹出Context Menu" /&
&/RelativeLayout&
package com.example.
import android.app.A
import android.os.B
import android.view.ContextM
import android.view.ContextMenu.ContextMenuI
import android.view.M
import android.view.MenuI
import android.view.SubM
import android.view.V
import android.widget.B
import android.widget.T
public class MenuActivity extends Activity {
private Button btnC
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
btnContext = (Button) findViewById(R.id.ContextButton);
registerForContextMenu(btnContext);
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
//当用户按下menu button按钮时显示的菜单
menu.add(0, 1, 1, "香蕉");
menu.add(0, 2, 2, "苹果");
//当用户按下一个菜单的某个选项时弹出的子菜单
SubMenu subMenu = menu.addSubMenu(1, 100, 100, "桃子");
subMenu.add(2, 101, 101, "大桃子");
subMenu.add(2, 102, 102, "小桃子");
return super.onCreateOptionsMenu(menu);
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getItemId() == 1){
Toast t = Toast.makeText(this, "你选的是苹果", Toast.LENGTH_LONG);
else if(item.getItemId() == 2){
Toast t = Toast.makeText(this, "你选的是香蕉", Toast.LENGTH_SHORT);
return true;
//Context Menu
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
if(v==btnContext){
menu.setHeaderTitle("这是1");
menu.add(200, 200, 200, "Context Menu 1");
menu.add(200, 201, 201, "Context Menu 2");
super.onCreateContextMenu(menu, v, menuInfo);
7、AutoCompleteTextView
&自动完成文本框,它实际上也是一个文本编辑框,可以理解为对EditText功能的扩展,它对输入的内容可以进行提示并且自动完成。本文会讲解常用属性设置,以及如何向AutoCompleteTextView增加提示数据.
  自动完成文本框(),可以从官方文档上看出,是从EditText继承而来,所以它实际上也是一个文本编辑框,只是多了一个自动提示输入补全的功能。功能类似于:当用户输入一定字符之后,自动完成文本框会显示一个下拉列表,供用户从中选择,当用户选择某个菜单项之后,AutoCompleteTextView会按照的选择自动填写该文本框。
  因为是继承自EditText,所以AutoCompleteTextView除了可以使提供用Edit的属性和方法之外,还支持如下一些特殊的属性及方法,这里只介绍一些常用的,具体请参见官方文档:
android:completionHint/setCompletionHint(CharSequence):设置出现下拉列表的提示标题。
android:completionTjreshold/setThreshold(int):设置至少输入几个字符才会显示提示。
android:dropDownHeight/setDropHeight(int):设置下拉列表的高度。
android:dropDownWidth/setDropWidth(int):设置下拉列表的宽度。
android:popupBackground/setDropDownbackgroundResource(int):设置下拉列表的背景。
填充选择数据
  在Android程序中,为了展示数据,通常会用到一个Adapter的接口。没错,这是一个接口,是连接后端数据和前端显示的桥梁,是data souce和UI(View)之间一个重要的纽带。下图展示了Adapter在Android程序中的关系:
对于,它是一个接口,Android为其声明了各种实现类,对于在AutoCompleteTextView控件中,一般使用即可完成功能,对于一些其他实现类的应用场景,以后会慢慢介绍。
  ArrayAdapter&T&继承自一个抽象类BaseAdapter,而这个抽象类实现了Adapter接口,所以继承关系应该是:Adapter&BaseAdater&ArrayAdapter&T&。
  从名字上可以看出,ArrayAdapter&T&是以一个数组的形式去存储数据的,它也确实是这么做的,并且可以传递一个数组对其进行构造。所以我们只需要填充一个数组对象,就完成ArrayAdapter对象的初始化工作,在把得到的ArrayAdapter对象传递给AutoCompleteTextView控件,即可对其进行选择数据设置。
布局文件:
&RelativeLayout xmlns:android="/apk/res/android"
xmlns:tools="/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" &
&AutoCompleteTextView
android:id="@+id/autotext"
android:completionHint="Famous Citi"
android:completionThreshold="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" /&
&/RelativeLayout&
package com.example.
import android.app.A
import android.os.B
import android.view.M
import android.view.MenuI
import android.widget.ArrayA
import android.widget.AutoCompleteTextV
public class AutoCompleteTextViewActivity extends Activity {
private AutoCompleteTextV
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete_text_view);
autotext=(AutoCompleteTextView)findViewById(R.id.autotext);
//设置数据源
String[] autoStrings=new String[]{"New York","Tokyo","beijing","london","Seoul Special","Los Angeles"};
//设置ArrayAdapter,并且设定以单行下拉列表风格展示(第二个参数设定)。
ArrayAdapter&String& adapter=new ArrayAdapter&String&(AutoCompleteTextViewActivity.this,
android.R.layout.simple_dropdown_item_1line, autoStrings);
autotext.setAdapter(adapter);
8、SeekBar
拖动条(SeekBar)和进度条非常相似,只是进度条采用颜色填充来表明进度完成的程度,而拖动条则通过滑块的位置来标识数值----而且拖动条允许用户拖动滑动块来改变值,因此拖动条通常用于对系统的某种数值进行调节,比如音量调节。
SeekBar允许用户改变拖动条的滑块外观,改变滑块外观通过如下属性来指定
android:thumb&&指定一个Drawable对象,该对象将作为自定义滑块。
为了让程序能响应拖动条滑块位置的改变,程序可以考虑为他绑定一个OnSeekBarChangerListener***器。
通过一个实例:通过滑动块来改变图片的透明度,来看看SeekBar。
&?xml version="1.0" encoding="utf-8"?&
&LinearLayout xmlns:android="/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
&ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="240px"
android:src="@drawable/world"
android:id="@+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="255"
android:thumb="@drawable/ic_launcher"
&/LinearLayout&
package com.example.
import android.app.A
import android.os.B
import android.view.M
import android.view.MenuI
import android.widget.ImageV
import android.widget.SeekB
import android.widget.SeekBar.OnSeekBarChangeL
public class SeekBarActivity extends Activity {
private ImageV
private SeekBar seekB
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seek_bar);
image = (ImageView)this.findViewById(R.id.image);
seekBar = (SeekBar)this.findViewById(R.id.seekbar);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
public void onStartTrackingTouch(SeekBar seekBar) {
//当拖动条的滑块位置发生改变时触发该方法
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
image.setAlpha(arg1);
效果如下:
阅读(...) 评论()

参考资料

 

随机推荐