Android常用控件总结

Notepad++编写 可以负责粘贴到其中去 看得更清楚。(内容包括了Android中的大部分常用控件及其事件的监听)
第一章
1.1Android中src文件夹包含项目的所有包及其资源文件,res文件夹包含了项目中所有的资源。比如:程序图标(drawable),布局文件(layout),常量(value),音频文件(raw)
R.java是在创建项目是自动生成的只读文件,不可更改此文件。R文件其作用:是定义项目中所有资源的索引文件。

1.2 AndroidManfest.xml 如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest //根节点,描述了packege包中所有的内容
xmlns:android="http://schemas.android.com/apk/res/android"//包命名空间的声明,使得Android中各种标准属性能在文件中使用,提供了大部分元素中的数据
package="Android.Summary"//引用程序包名
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />//使用SDK版本号

<application//包含package中application级别组件声明的根节点,可包含application的一些全局和默认的属性,如标签label,icon,主题,必要的全限。注意:一个manifest中只能包含一个或0个application
android:icon="@drawable/icon" //应用程序图标
android:label="@string/app_name">//应用程序名字
<activity android:name=".SummaryActivity"//Activity用来与用户交互的主要工具,是用户打开程序的初始界面.此处为引用程序默认启动的Activity
android:label="@string/app_name">
<intent-filter>///描述了Activity的启动时间和位置,另外为了支持查找Activity可以包含一个或多个<intent-filter>
<action android:name="android.intent.action.MAIN" />//acton 为组件支持的Intent action
<category android:name="android.intent.category.LAUNCHER" />//categor 为组件支持的Intent category 这里指定了引用程序的默认启动的Activity
</intent-filter>
</activity>
<activity android:name = "Activity02"></activity>//在此对新增的Activity进行注册。如果在不同的包中注意声明是将包名带上
</application>
</manifest>

1.3String.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>//此处定义了两个字符串资源,即定义了app_name,hello常量
<string name="hello">Hello World, SummaryActivity!</string>
<string name="app_name">Summary</string>
</resources>
如何使用这个资源呢?如下:
Resources r = this.getContext().getResources();//通过Context的getResource()实例化一个Resources对象
String app_name = ((String)r.getString(R.string.app_name));//然后通过getString()方法取得指定的索引的字符串。项目中所有常量都可以在String.xml文件中定义
String hello = ((String)r.getString(R.string.hello));

1.4 main.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"//LinearLayout 线程版面配置
android:orientation="vertical"//版面配置的方式。此为自上到下为垂直配置,"horizontal"为水平配置
android:layout_width="fill_parent"//定义当前视图在屏幕上所占的宽度,"fill_parent"为填充整个屏幕宽度
/*android:layout_weight="50"*///用于给一个布局中多个视图的重要度赋值
android:layout_height="fill_parent"//定义当前视图在屏幕上所占的高度,...........................高度
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content" //随着视图的栏位的不同而改变这个视图的高度或宽度
android:text="@string/hello"//在视图上显示的内容,此处引用了@String中的hello字符串
/>
</LinearLayout>

1.5 src下的java 如下:
package Android.Summary;

import android.app.Activity;
import android.os.Bundle;

public class SummaryActivity extends Activity {//继承自Activity
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){//重写onCreate()方法
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//设置要显示的布局
}
}

第二章
2.1Android应用程序由四个模块组成:Activity,Service,Intent,ContentProvider(注意:一个应用程序不一定包含全部的四个模块).
在使用时必须在AandroidManfest中进行声明。
Activity可以理解为用户看到屏幕,主要用于处理应用程序的整体性工作。如:
a.监听系统事件,触屏事件,为用户显示指定的View,启动其他Activity等。
b.所有应用的Activity都继承于android.app.Activity,该类是Android提供的基层类。
c.一个Activity通常就是一个单独的屏幕。
d.每一个活动都被实现为一个独立的类。
e.大多数的应用程序都是由多个Activity组成。

Intent Aandroid中主要用Intent类实现从一个Activity跳转到另一个Activity。在Intent的描述结构中,有两个重要的部分:动作和对应的数据。
典型的动作有MAIN,VIEW,PICK,EDIT.而动作对应的数据则以URI的形式表示。例如:要查一个人的联系方式,需要创建一个动作类型View的Intent
,以及一个表示这个人的URI.
Intent的使用:
button1.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent();//创建一个Intent对象
intent.setClass(Activity01.this,Activity02.class);//指明要启动的另一Activity02
startActivity(intent); //启动一个新的Activity
Activity01.this.finish();//关闭当前Activity01
}
});
这里需要注意在Android中对新启动的Activity进行声明。声明方式:
<activity android:name = "Activity02"></activity> //注意:如果在不同的包中在声明是还要加上包名

IntentReceiver
如果希望Android应用能够对外部事件(如电话打入时,数据网络可用时,)做出响应,可用使用IntentReceiver.虽然IntentReceiver在如上事件发生
时会使用NotificationManager通知用户,但它并不能生产UI。IntentReceiver可以在AndroidManifest.xml中注册,也可在代码中使用Context.registerReceiver
进行注册。当IntentReceiver被触发时,系统会在需要的时候启动应用。各种应用还可以通过ContentReceiver()将他们自己的IntentReceiver广播出去。???????

Content Provider
作用:主要用于不同应用程序中的数据的传递。
Content Provider 是一个特殊的存储数据的类型。
Android自身提供现成的Content Provider:Contacts ,Browser,CallLog,Settings,MediaStore
应用可用通过唯一的ContentResolver界面来使用具体的Conten Provider,然后可以用ContentResolver提供的方法来使用你需要的Content Provider
其中,ContentResolver提供的方法有query(),insert(),update()等。
URI----String形式的Content Provider的完整路径。

下面这个这个例子通过ContentProvider获取电话本中的数据,然后显示到TextView中去。
public class Activity01 extends Activity{
public void onCreate(Bundle savedInstanceState){
TextView textView = new TextView(this);//得到TextView对象
String string = "";
super.onCreate(savedInstanceState);

ContentResolver resolver = getContentResolver();//得到ContentResolver对象
Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);//取得电话本中开始一项的光标,通过query方法查询出符合标准的电话本记录
//向下移动光标
while(cursor.moveToNext()){
//取得联系人名字
int name_index = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String name = cursor.getString(name_index);
//取得电话号码
int number_index = cursor.getColumnIndex(PhoneLookup.NUMBER);
String number = cursor.getString(number_index);

string +=(name+":"+number+"\n");
}
cursor.close();
textView.setText(string);//设置TextView显示的内容
setContentView(textView);//显示到屏幕上 其实TextView也是View的一种
}
}
注意:在使用这些模块中用到了读取联系人的API,所以必须在AndroidManifest.xml中声明
声明方式为:
<uses_permission
android:name="android.permission.READ_CONTACTS">
</uses-permission>

Service 后台服务,没有界面
启动service方法:
a.Context.startService()
b.Context.bindService()//与上一种方法不同处 如果这个Service没有处于启动状态,则将其启动

下面这个例子以Activity中的俩个控件来控制播放一首Mp3. (例中:需要在res文件夹中创建一个raw文件夹 然后放入一首MP3)

public class Activity01 extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//从main.xml布局中获得Button对象
Button button_start = (Button)findViewById(R.id.start);
Button button_stop = (Button)findViewById(R.id.stop);
//设置按钮(Button)监听
button_start.setOnClickListener(start);
button_stop.setOnClickListener(stop);
}
//开始按钮
private OnClickListener start = new OnClickListener(){
public void onClick(View v){
//开启Service
startService(new Intent("com.yarin.Android.MUSIC"));
}
};
//停止按钮
private OnClickListener stop = new OnClickListener(){
public void onClick(View v){
//停止Service
stopService(new Intent("com.yarin.Android.MUSIC"));
}
};
}

public class MusicService extends Service{
//MediaPlayer对象
private MediaPlayerplayer;

public IBinder onBind(Intent arg0){
return null;
}
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
//这里可以理解为装载音乐文件
player = MediaPlayer.create(this, R.raw.test);
//开始播放
player.start();
}

public void onDestroy(){
super.onDestroy();
//停止音乐-停止Service
player.stop();
}
}

AndroidManifest.xml文件中
<service android:name=".MusicService">
<intent-filter>
<action android:name="com.yarin.Android.MUSIC" />
<category android:name="android.intent.category.default" />
</intent-filter>
</service>

2.2Aandrod的生命周期
public class Activity02 extends Activity{
private static final StringTAG= "Activity02";

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Log.v(TAG, "onCreate");
}
public void onStart(){
super.onStart();
Log.v(TAG, "onStart");
}
public void onResume(){
super.onResume();
Log.v(TAG, "onResume");
}
public void onPause(){
super.onPause();
Log.v(TAG, "onPause");
}
public void onStop(){
super.onStop();
Log.v(TAG, "onStop");
}
public void onDestroy(){
super.onDestroy();
Log.v(TAG, "onDestroy");
}
public void onRestart(){
super.onRestart();
Log.v(TAG, "onReStart");
}
}
这些方法都是系统自动调用的。

第三章
3.1 事件处理
* 控件事件通过设置其控件的监听器来监听并处理事件
* 按键按下事件:通过重写onKeyDown方法
* 按键弹起事件:通过重写onKeyUp方法
* 触笔点击事件:通过实现onTouchEvent方法
* 示例中使用了Toast控件:
* Toast.makeText(this, string, Toast.LENGTH_SHORT).show();

public class Activity01 extends Activity{

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获得Button对象
Button button_ok = (Button) findViewById(R.id.ok);

button_ok.setOnClickListener(new Button.OnClickListener() {-------------------------------------------------------//设置Button控件监听器
public void onClick(View v){
//这里处理事件
DisplayToast("点击了OK按钮");
}
});
}

/* 按键按下所触发的事件 */
public boolean onKeyDown(int keyCode, KeyEvent event){
switch (keyCode){
case KeyEvent.KEYCODE_DPAD_CENTER:
DisplayToast("按下:中键");
break;
case KeyEvent.KEYCODE_DPAD_UP:
DisplayToast("按下:上方向键");
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
DisplayToast("按下:下方向键");
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
DisplayToast("按下:左方向键");
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
DisplayToast("按下:右方向键");
break;
}
return super.onKeyDown(keyCode, event);
}
/* 按键弹起所触发的事件 */
public boolean onKeyUp(int keyCode, KeyEvent event){
switch (keyCode){
case KeyEvent.KEYCODE_DPAD_CENTER:
DisplayToast("弹起:中键");
break;
case KeyEvent.KEYCODE_DPAD_UP:
DisplayToast("弹起:上方向键");
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
DisplayToast("弹起:下方向键");
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
DisplayToast("弹起:左方向键");
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
DisplayToast("弹起:右方向键");
break;
}
return super.onKeyUp(keyCode, event);
}
//用于响应按键重复点击,官方API指出onKeyMultiple方法总是返回false,即它没有handle,因此必须重写才能实现-------------------此方法没用过具体情况怎么样不是很清楚?
public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event){

return super.onKeyMultiple(keyCode, repeatCount, event);
}

/* 触笔事件 */
public boolean onTouchEvent(MotionEvent event){
int iAction = event.getAction();//利用getAction得到所执行的动作
if (iAction == MotionEvent.ACTION_CANCEL ||
iAction == MotionEvent.ACTION_DOWN ||
iAction == MotionEvent.ACTION_MOVE){
return false;
}
//得到触笔点击的位置
int x = (int) event.getX();
int y = (int) event.getY();
//将获得的坐标转成String类型的方法
DisplayToast("触笔点击坐标:("+Integer.toString(x)+","+Integer.toString(y)+")");

return super.onTouchEvent(event);
}

/* 显示Toast */
public void DisplayToast(String str){
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
}
我们分析了一些常用事件处理方式。每一个键都对应一个键值。当然也可根据需要来改变一些键的功能,需要我们自己构建KeyEvent对象------------------有待进一步学习
构造KeyEvent对象的几种方法:
KeyEvent(int action,int code);
KeyEvent(long DownTime,long EventTime,int action,int code,int repeat);
KeyEvent(long DownTime,long EventTime,int action,int code,int repeat,int metState);
KeyEvent(long DownTime,long EventTime,int action,int code,int repeat,int metState,int device,int scancode);
KeyEvent(long DownTime,long EventTime,int action,int code,int repeat,int metState,int device,int scancode,int flags);
KeyEvent(KeyEvent origEvent,long EventTime,int newRepart);
例:
public class Activity01 extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onKeyDown(int keyCode, KeyEvent event){
//这里构建KeyEvent对象,其功能为返回键的功能
//因此我们按任意键都会执行返回键功能
KeyEvent key = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);

//这里传入的参数就是我们自己构建的KeyEvent对象key
return super.onKeyDown(key.getKeyCode(), key);
}
}
3.2常用控件
Button
xml设计
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></Button>

代码设计 Button button = new Button(this);
button.setText("我是Button");
button.setWidth(123); //设置宽度
button.setHeight(123); //设置高度
button.setTextColor(Color.BLUE); //设置文字颜色
button.setTextSize(123); //设置字体大小
button.setBackgroundColor(Color.BLUE); //设置控件背景色

监听器
button.setOnClickListener(new Button.OnClickListener(){//设置按钮的事件监听
public void onClick(View v){
//处理按钮事件产生一个Toast.利用button.getText()得到按钮显示的内容
Toast toast = Toast.makeText(Activity01.this, "你点击了“"+button.getText()+"”按钮!", Toast.LENGTH_LONG);
//设置toast显示的位置
toast.setGravity(Gravity.TOP, 0, 150);
//显示该Toast
toast.show();
}
});
-----------------------------------------------------------------------------------------------------------------------------
TextView 一个用来显示文本的控件
xml设计 <TextView
android:id= "@+id/textView" //设置id
android:layout_width ="fill_parent"//宽度充满全屏
android:layout_height="wrap_content"//高度随控件变化
android:layout_height="2dip"
android:textColor=""
android:background="#aaa00"//背景颜色
android:text="你好"/>
android:paddingLeft="50px"
android:paddingTop="5px"
android:paddingBottom="5px"
android:textSize="30sp"
android:singleLine="true"
android:layout_below="@id/imageView_handler"//在什么下
android:gravity ="left" //用于设置View中内容相对于View组件的对齐方式,
android:layout_gravity//用于设置View组件相对于Container的对齐方式。
android:paddingLeft="30px" // 按钮上设置的内容离按钮左边边界30个像素
android:layout_marginLeft="30px" //整个按钮离左边设置的内容30个像素
android:layout_weight="1"//控件权重 即占的比例 默认值为0
android:gravity="center_horizontal"//水平居中
android:padding="3dip"



代码设计 TextView textView = new TextView(this);//声明对象
textView.setTextColor(Color.RED);//设置字体颜色
textView.setTextSize(20);//设置字体大小
textView.setBackgroundColor(Color.BLUE);//控件背景色
textView.setText("你好")//显示的文字
textView.setHeight
textView.setWidth
textView.setVisibility(GONE/VISIBLE);//设置为不可见/可见
textView.setGravity(Gravity.CENTER);//设置文字权重


监听器 TextView textView = new TextView(this);//得到对象
textview.setOnClickListener(new TextView.OnClickListener(){-------------------------------------------TextView监听器
public void onClick(View v){
}
});
-------------------------------------------------------------------------------------------------------------------------------
ImageButton 带图标的按钮
xml设计
<ImageButton
android:id= "@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/qq" //在xml设计所使用的图片
/>

代码中设计
imageButton.setImageDrawable(getResources().getDrawable(R.drawable.image2));//在代码中设计使用的图片(得到对象后)

监听器
imageButton.setOnClickListener(new Button.OnClickListener() {---------------------------------------------ImageButton监听器

@Override
public void onClick(View v) {
//创建对话框
Dialog dialog = new AlertDialog.Builder(ImageButton_Dialog.this)
.setTitle("ImageButton2")
.setMessage("跳转到系统图片")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
imageButton2.setImageDrawable(getResources().getDrawable(android.R.drawable.sym_action_call));
}
}).create();
dialog.show();
}
});
-------------------------------------------------------------------------------------------------------------------------------
EditText
xml设计
<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_x="29px"
android:layout_y="33px"
android:hint="请输入账号"//设置当m_EditText中为空时提示的内容
/>

代码设计 EditText editText = new EditText(this);//得到EditText对象
editText.setTextSize(20);//设置字体大小
editText.setHint("请输入账号");//设置当m_EditText中为空时提示的内容
监听器
editText.setOnKeyListener(new EditText.OnKeyListener(){-----------------------------------------EditText监听器
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2){

// 得到文字,将其显示到TextView中
m_TextView.setText("文本框中内容是:" + m_EditText.getText().toString());
return false;
}
});
-----------------------------------------------------------------------------------------------------------------
CheckBox 多项选择 需要对没有按钮设置监听器
xml设计
<CheckBox
android:id="@+id/checkBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/CheckBox4"
>
监听器
checkBox1.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {//对每个选项设置事件监听-------------------CheckBox监听器
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if(m_CheckBox1.isChecked()){
DisplayToast("你选择了:"+m_CheckBox1.getText());
}
}
});
-------------------------------------------------------------------------------------------------------------------
Spinner 下拉列表
下面一个例子将可选内容通过ArrayAdapter和下拉列表连接起来。设置监听器 通过setVisibility方法设置当前显示项
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/TextView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Spinner
android:id="@+id/Spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
/>
</LinearLayout>

public class Activity01 extends Activity{
private static final String[]string= { "O型", "A型", "B型", "AB型", "其他" };

private TextViewm_TextView;
private Spinnerm_Spinner;
private ArrayAdapter<String>adapter;

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

m_TextView = (TextView) findViewById(R.id.TextView1);
m_Spinner = (Spinner) findViewById(R.id.Spinner1);

//将可选内容与ArrayAdapter连接
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, string);

//设置下拉列表的风格
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

//将adapter添加到m_Spinner中
m_Spinner.setAdapter(adapter);

//添加Spinner事件监听
m_Spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {--------------------------Spinner监听器

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
m_TextView.setText("你的血型是:" + string[arg2]);
//设置显示当前选择的项
arg0.setVisibility(View.VISIBLE);
}

@Override
public void onNothingSelected(AdapterView<?> arg0){
// TODO Auto-generated method stub
}
);
}
}
}
------------------------------------------------------------------------------------------------------
RadioGroup , RadioButton 单选选择控件
一个单选选择由两部分组成,分别是前面的选择按钮和后面的内容。按钮通过RadioButton来实现,答案通过RadioGroup来实现
如果确定是选择哪一项那就要设置监听器setOnCheckedChangeListener.
下面有一例子:本例中使用到了String.xml文件来定义常量。
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Android底层是基于什么操作系统?</string>
<string name="app_name">Examples_04_07</string>
<string name="RadioButton1">Windows</string>
<string name="RadioButton2">Linux</string>
<string name="RadioButton3">Moc os</string>
<string name="RadioButton4">Java</string>
</resources>

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/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<RadioGroup
android:id="@+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_x="3px"
android:layout_y="54px"
>
<RadioButton
android:id="@+id/RadioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/RadioButton1"
/>
<RadioButton
android:id="@+id/RadioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/RadioButton2"
/>
<RadioButton
android:id="@+id/RadioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/RadioButton3"
/>
<RadioButton
android:id="@+id/RadioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/RadioButton4"
/>
</RadioGroup>
</LinearLayout>

public class Activity01 extends Activity{
TextViewm_TextView;
RadioGroupm_RadioGroup;
RadioButtonm_Radio1, m_Radio2, m_Radio3, m_Radio4;

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

m_RadioGroup = (RadioGroup) findViewById(R.id.RadioGroup01);//获得RadioGroup对象
m_Radio1 = (RadioButton) findViewById(R.id.RadioButton1);//获得4个RadioButton对象
m_Radio2 = (RadioButton) findViewById(R.id.RadioButton2);
m_Radio3 = (RadioButton) findViewById(R.id.RadioButton3);
m_Radio4 = (RadioButton) findViewById(R.id.RadioButton4);

/* 设置事件监听 */
m_RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {---------------------------RadioGroup监听器
@Override
public void onCheckedChanged(RadioGroup group, int checkedId){

if (checkedId == m_Radio2.getId()){
DisplayToast("正确答案:" + m_Radio2.getText() + ",恭喜你,回答正确!");
}else{
DisplayToast("请注意,回答错误!");
}
}
});
}
public void DisplayToast(String str)//显示Toast{
Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
//设置toast显示的位置
toast.setGravity(Gravity.TOP, 0, 220);
//显示该Toast
toast.show();
}
}
-----------------------------------------------------------------------------------------------------------
AutoCompletTextView 和 MultiAutoCompleteTextView 作用:自动提示 下面例中用到了ArrayAdapter
autoCompletTextView.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"
>
<AutoCompleteTextView
android:id= "@+id/autoCompleteTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<MultiAutoCompleteTextView
android:id= "@+id/multiAutoCompleteTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

//如何实现如果输入的字符不在其范围内的也能得到提示 是继承TextWatcher?
public class Control_Auto extends Activity {
//implements TextWatcher{}
public TextView textView_auto;

private static final String[] string ={"ni hao","ni hao ","ni hao ma","ni zheng de hao ma","nshis"};

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.autocompletetextview);

//将可选内容与适配器ArrayAdapter连接
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,string);

MultiAutoCompleteTextView multiAutoCompletTextView = (MultiAutoCompleteTextView)findViewById(R.id.multiAutoCompleteTextView);
AutoCompleteTextView autoCompleteTextView =(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);

autoCompleteTextView.setAdapter(adapter);//将adapter添加到AutoCompletTextView中去
multiAutoCompletTextView.setAdapter(adapter);//将adapter添加到MultAutoCompleteTextView中去

multiAutoCompletTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
}
}

/* //autoCompleteTextView.addTextChangedListener(this);---此为设置监听?
* 例子中没有涉及到的属性(可在布局文件中设置):
AutoCompleteTextView是EditText的子类,所以你可以对它的对象进行诸如外观/字体/颜色等属性值的设置。
  completionThreshold:它的值决定了你在AutoCompleteTextView至少输入几个字符,它才会具有自动提示的功能。另,默认最多提示20条。
  dropDownAnchor:它的值是一个View的ID,指定后,AutoCompleteTextView会在这个View下弹出自动提示。
  dropDownSelector:应该是设置自动提示的背景色之类的。
  dropDownWidth:设置自动提示列表的宽度。
你可以通过setAdapter()来给AutoCompleteTextView添加一个包含候选值列表的适配器(adapter)。--------此处没实现过?
然而,由于用户可以输入一些不在候选值列表的数据,AutoCompleteTextView不支
持selection listener。不过,你可以注册一个TextWacther用于当用户输入文本发生变化时发出通知。
----------------------------------------------------------------------------------------------------------------------
DatePicker,TimePicker 日期和时间
下例中首先需要在布局文件中定义DatePicker和TimePicker,然后通过Canlendar类获得系统时间,接着通过init方法将日期传给DatePicker,
并设置OnDateChangedListener来监听日期改变,当时间被改变时需要设置setOnTimeChangedListener监听来设置时间。
datepicker_timepicker.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/textView_date_time1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
/>
<DatePicker
android:id= "@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TimePicker
android:id= "@+id/timerPicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id= "@+id/button_date_time1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="日期"
/>
<Button
android:id= "@+id/button_date_time2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="时间"
/>
</LinearLayout>

public class Date_Time extends Activity{//如何实现日期随系统不断变化?要联网才能实现?如何变换DatePicker和TimePicker样式(如颜色 ,图片等)?
Calendar calendar;
TextView textView_date_time;
Button button_date_time1;
Button button_date_time2;
DatePicker datePicker;
TimePicker timePicker;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.datepicker_timepicker);
calendar = Calendar.getInstance();//得到日历对象

textView_date_time = (TextView)findViewById(R.id.textView_date_time1);
button_date_time1 = (Button)findViewById(R.id.button_date_time1);
button_date_time2 = (Button)findViewById(R.id.button_date_time2);
datePicker = (DatePicker)findViewById(R.id.datePicker);
timePicker = (TimePicker)findViewById(R.id.timerPicker);

button_date_time1.setWidth(50);
button_date_time1.setHeight(60);
button_date_time1.setTextColor(Color.BLUE);

timePicker.setIs24HourView(true);//设置为24小时制

//将日历初始化为当前系统日期 , 并设置监听器
datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), --------------------------------------------DatePicker监听器
calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {//OnDateChangedListener监听日期的变化

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
//设置日期
calendar.set(1987,10,15);
}
});

timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {-------------------------------------------TimePicker监听器

@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

//设置时间
//calendar.set(1987,10,29,23,23,23);//年 月 日 小时 分钟 秒
textView_date_time.setText("当前时间:"+hourOfDay+" : "+minute);
}
});

button_date_time1.setOnClickListener(new Button.OnClickListener(){//日期的监听---------------------------Button控件中设置DatePicker监听器

@Override
public void onClick(View v) {
new DatePickerDialog(Date_Time.this,new DatePickerDialog.OnDateSetListener(){

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
//设置日历
textView_date_time.setText("农历"+year+" 年 "+monthOfYear+" 月 "+dayOfMonth+" 日 ");
}
},calendar.get(Calendar.YEAR) , calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
}
});

button_date_time2.setOnClickListener(new Button.OnClickListener(){//时间的监听器----------------------------Button控件中设置TimePicker监听器

@Override
public void onClick(View v) {new TimePickerDialog(Date_Time.this, new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

//设置时间
textView_date_time.setText("北京时间:"+hourOfDay+" : "+minute);
}
},calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();
}});
}

}


------------------------------------------------------------------------------------------------------------
Menu 操作应用程序的菜单选项
第一个例子:通过XML文件来实现
menu_com.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/about"
android:title="关于"/>
<item android:id="@+id/skip"
android:title="到menu_add中去"/>
</menu>

public class Menu_Xml extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.此为所以显示的界面id);
}
public boolean onCreateOptionsMenu(Menu menu){//创建menu
MenuInflater inflater = getMenuInflater();
//设置menu界面
inflater.inflate(R.layout.menu_com, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){//处理菜单事件
switch(item.getItemId()){
case R.id.about:
Menu_Xml.this.finish();
case R.id.skip:
Intent intent = new Intent();
intent.setClass(Menu_Xml.this, Menu_add.class);//跳转到Menu_add中去
startActivity(intent);
Menu_Xml.this.finish();
}
return true;

}
}
===========================================================================================================
第二个例子:在代码中生成Menu 此例中包含俩个方法 注意区分注释掉的为另一种增加Menu的方法
public class Menu_add extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.toast);
}
public boolean onCreateOptionsMenu(Menu menu){//创立menu
/*为Menu添加内容参数:Menu.add()方法第一个参数表示给这个新增的菜单项分配一个分组号;
* 第二个参数表示给这个新增的菜单项分配一个唯一标识id;第三个参数为菜单项的序号;
* 第四个参数为菜单项的标题。
我们可以通过调用Menu.setItemShown()或者Menu.setGroupShown()方法来显示或隐藏一些菜单项。
这里要注意的一个地方是:菜单项的显示顺序是按代码中添加的顺序来的,也就是说Menu.add()方法
只能在菜单的最后面新增一个菜单项。另外,第一个参数的分组标识,不会改变菜单项的显示顺序。

方法一:
//menu.add(0,0,0,R.string.menu1);方法一
//menu.add(0,1,1,R.string.menu2);
方法二:
SubMenu subMenu = menu.addSubMenu(1, 1, 2, "选项");//此方法和menu方法类似
subMenu.add(13,13,13, "到Content_Menu");
subMenu.add(13,24,24,"到Menu_Xml");

return true;
}
public boolean onOptionsItemSelected(MenuItem item){//处理Menu事件
switch(item.getItemId()){//getItemId()得到菜单项的ID,即上面的第二个参数
case 13:
Intent intent1 = new Intent();
intent1.setClass(Menu_add.this, Context_Menu.class);
startActivity(intent1);
Menu_add.this.finish();
case 23:
Intent intent = new Intent();
intent.setClass(Menu_add.this, Menu_Xml.class);//跳转到其他界面中去
startActivity(intent);
Menu_add.this.finish();
break;
}
return true;
}
}
==========================================================================================================
第三个例子:Context Menu的创建:
概述:Android 的上下文菜单类似于 PC 上的右键菜单。当为一个视图注册了上下文菜单之后,
长按(2 秒左右)这个视图对象就会弹出一个浮动菜单,即上下文菜单。任何视图都可以
注册上下文菜单,不过,最常见的是用于列表视图ListView的item。

注意:Android 的上下文菜单不支持图标或快捷键。
创建一个上下文菜单的步骤:
1. 覆盖 Activity 的 onCreateContenxtMenu() 方法,调用 Menu 的 add 方法添加菜单项(MenuItem)。
2. 覆盖 Activity 的 onContextItemSelected() 方法,响应上下文菜单菜单项的单击事件。
3. 调用 registerForContextMenu() 方法,为视图注册上下文菜单。
menu_com2.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/textView_context_Menu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="长按我 我才会出现 TextView"
/>
<Button
android:id= "@+id/button_context_Menu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="长按我 我才会出现 Button"
/>
</LinearLayout>

public class Context_Menu extends Activity{
public TextView textView_context_Menu;
public Button buttont_context_Menu;

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_com2);
textView_context_Menu = (TextView)findViewById(R.id.textView_context_Menu);
buttont_context_Menu = (Button)findViewById(R.id.button_context_Menu);

registerForContextMenu(textView_context_Menu);
registerForContextMenu(buttont_context_Menu);
//这里的registerForContextMenu()也可以用下面的语句替代
//getContentView().setOnCreateContextMenuListener(this);
}
//创建Context Menu
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
if(v==textView_context_Menu){
menu.setHeaderTitle("这个是什么?");
menu.add(0,0,0,"苹果");
menu.add(0,1,1,"猕猴桃");
}else if(v==buttont_context_Menu){
menu.setHeaderTitle("我知道是什么了!");
menu.add(2,2,2,"不是苹果");
menu.add(2,3,3,"就是猕猴桃");
}
super.onCreateContextMenu(menu, v, menuInfo);
}
//菜单单击响应
@Override
public boolean onContextItemSelected(MenuItem item){
//获取当前被选择的菜单项的信息
switch(item.getItemId()){
case 1:
Toast toast=Toast.makeText(Context_Menu.this, "你点击了"+textView_context_Menu.getText(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 100, 300);
toast.show();
break;
case 3:
Toast toast1=Toast.makeText(Context_Menu.this, "你点击了"+buttont_context_Menu.getText(), Toast.LENGTH_LONG);
toast1.setGravity(Gravity.TOP, 100, 300);
toast1.show();
break;
}
return true;
}
}
==========================================================================================================
第四个例子:动态Menu
此为动态Menu的实现 ,采用的是代码布局(非XML布局)。此种Memu用在什么情况下,具体该怎么做?

public class Trends_Menu extends Activity{
LinearLayout linearLayout;
TextView textView;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
linearLayout = new LinearLayout(this);
linearLayout.setBackgroundColor(android.graphics.Color.BLUE);//设置背景色
linearLayout.setOrientation(linearLayout.VERTICAL);//设置布局方向

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
textView= new TextView(this);//创建TextView对象
textView.setBackgroundColor(Color.YELLOW);//设置背景颜色
textView.setText("Trends_Men");
textView.setTextSize(50);
//textView.setHeight(50);
//textView.setWidth(100);
textView.setTextColor(Color.RED);//设置字体颜色

linearLayout.addView(textView,params);//将textView添加到linearLayout中去
setContentView(linearLayout);//设置ui布局
}
public boolean onPrepareOptionsMenu(Menu menu){
String string = textView.getText().toString();
if(string.equals("Trends_Menu")){
menu.clear();//清掉菜单
MenuItem item = menu.add(0,1,1,"to Menu");
item.setIcon(android.R.drawable.alert_dark_frame);//android自带的图标
}
if(string.equals("Menu")){
menu.clear();
MenuItem item = menu.add(1,2,2,"to Trends_Menu");
item.setIcon(android.R.drawable.alert_light_frame);
}
menu.add(0,2,2,"Now is"+string);
return super.onPrepareOptionsMenu(menu);
}
}

----------------------------------------------------------------------------------------------------------
ListView 一个用来显示列表的控件
xml设计
代码设计
第一个例子:
public class ListView3 extends ListActivity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

String[] string={"华中科技","天龙大厦","科技园","天天乐园"};//string 是用来要存放的数据

//android.R.layout.simple_expandable_list_item_1为XML的配置文件, 用来设置列表中每一行的窗口
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,string));
}
}
* 每一个ListActivity系统都会给他一个默认的系统布局,所以不需要设置setConteView(),
* 但是我们也可以指定窗口的布局(如simpleadapter.com包中文件的配置文件simpleadapter1,2)
* 在配置文件中要注意的是android:list 是系统自定义的不是随便可以取的,否则会出现找不到ListView
================================================================================================================
第二个例子:
textView_chrild.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/textView_chrild"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="50px"
android:paddingTop="5px"
android:paddingBottom="5px"
android:text="no date"
android:textSize="30sp"
/>
</LinearLayout>
---------------------------------------------------------------------------------------
textView_group.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/textView_group"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="60px"
android:paddingTop="10px"
android:paddingBottom="10px"
android:text="no date"
android:textSize="25sp"
/>
</LinearLayout>
-------------------------------------------------------------------------------------------
<?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"
>
<ExpandableListView
android:id= "@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
/>
<TextView
android:id= "@+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="No date"
/>
</LinearLayout>
---------------------------------------------------------------------------------------------
public class MyActivity extends ExpandableListActivity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expandable);
//定义一个List,该List对象为一级条目提供数据
List<Map<String,String>> list1 = new ArrayList<Map<String,String>>();
Map<String,String> map1 = new HashMap<String,String>();
Map<String,String> map2 = new HashMap<String,String>();
map1.put("list1", "map1");
map2.put("list1", "map2");
list1.add(map1);
list1.add(map2);
//定义一个List,该List对象为第一个一级条目 提供数据
List<Map<String,String>> list21 = new ArrayList<Map<String,String>>();
Map<String,String> map21 = new HashMap<String,String>();
Map<String,String> map22 = new HashMap<String,String>();
map21.put("list", "map21");
map22.put("list", "map22");
list21.add(map21);
list21.add(map22);
//定义一个List,该List对象为第二个一级条目提供数据
List<Map<String,String>> list31 = new ArrayList<Map<String,String>>();
Map<String,String> map31 = new HashMap<String,String>();
//Map<String,String> map32 = new HashMap<String,String>();
map31.put("list", "map31");
//map32.put("ni shi", "fdsa");
list31.add(map31);
//list31.add(map2);

//定义一个List,该List对象用来存储所有二级条目对象
List<List<Map<String,String>>> list0 = new ArrayList<List<Map<String,String>>>();
list0.add(list21);
list0.add(list31);

SimpleExpandableListAdapter simple = new SimpleExpandableListAdapter(
this,//context
list1,//一级条目数据
R.layout.expandable_group,//用来设置一级条目样式的布局文件
new String[]{"list1"}, //指定一级条目数据的Key
new int[]{R.id.textView_group},//指定一级条目数据显示的控件id
list0, //二级条目数据
R.layout.expandable_chrild,//用来设置二级条目样式的布局文件
new String[]{"list"}, //指定二级条目数据的Key
new int[]{R.id.textView_chrild});//指定二级条目数据显示的控件id

setListAdapter(simple);//将SimpleExpandableListAdapter对象设置给当前的Activity
}
}
=========================================================================================================================
第三个例子:自定义ListView
public class ImageTextView extends LinearLayout{
public TextView textView;
public ImageView imageView;

public ImageTextView(Context context, String string,Drawable drawable) {-----------------------------------* 注意这里并没用在xml定义控件
super(context);
// TODO Auto-generated constructor stub
this.setOrientation(VERTICAL);//设置为水平布局
imageView = new ImageView(context);
imageView.setImageDrawable(drawable);
imageView.setPadding(2, 5, 5, 0);//设置位置
addView(imageView,new LinearLayout.LayoutParams(40,30));

textView = new TextView(context);
textView.setText("title");
textView.setTextSize(20);
addView(textView,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,30));

textView = new TextView(context);
textView.setText("title");
textView.setTextSize(20);
addView(textView,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,30));
}
* 这是一个线性布局的View,其中包含一个TextView 和一个 ImageView.
* 且为垂直布局
}
--------------------------------------------------------------------------------------------------------------------
public class ListCombinAdapter extends BaseAdapter{--------------------------------------------------------------------------继承BaseAdapter 且必须重写五个函数
private Context wcontext;
private List<ImageTextView> list;

public ListCombinAdapter(Context context){
this.wcontext=context;
list = new ArrayList<ImageTextView>();
}
@Override
public int getCount() {
return list.size();//得到List对象数组的大小
}
@Override
public Object getItem(int position) {
return list.get(position);//得到对象在List数组中的位置
}
@Override
public long getItemId(int position) {
return (long)position;
}
public long getPosition(Object item){
return list.indexOf(item);//得到对象在list中的索引
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {//得到一个显示在屏幕上的View
ImageTextView imageTextView;
if(convertView == null){//判断原来的View是否存在 如果不存在利用ImageTextView创建一个View
imageTextView = new ImageTextView(wcontext,(String)list.get(position).textView.getText(),list.get(position).imageView.getDrawable());
}else{
imageTextView = (ImageTextView)convertView;//强制转型
imageTextView.textView = list.get(position).textView;
imageTextView.imageView = list.get(position).imageView;
}
return imageTextView;
}
public void addItem(String text,Drawable drawable){
list.add(new ImageTextView(wcontext,text,drawable));//将创建好的ImageTextView对象加入到list中去
}
}
-------------------------------------------------------------------------------------------------------------------
public class ListView4Activity extends ListActivity {//定制自己的adapter
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);//不需要此项
ListCombinAdapter listCombinAdapter = new ListCombinAdapter(this);
listCombinAdapter.addItem("不知道此处的字符串起什么作用",getResources().getDrawable(R.drawable.image2));
listCombinAdapter.addItem("不知道此处的字符串起什么作用", getResources().getDrawable(R.drawable.image3));
setListAdapter(listCombinAdapter);
}
}
=================================================================================================================
第四个例子:
simpleadapter2.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">
<LinearLayout android:id="@+id/listLinearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ListView android:id="@id/android:list"//注意此处是ListView在xml文件中的id形式为固定的否则将找不到------------ListView在XML文件中
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:scrollbars="vertical" />
</LinearLayout>
</LinearLayout>
---------------------------------------------------------------------------------------------------------------------
<?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"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="1dip"
android:paddingBottom="1dip">
<TextView
android:id="@+id/user_name"
android:layout_width="180dip"
android:layout_height="30dip"
android:textSize="10pt"
android:singleLine="true" />
<TextView
android:id="@+id/user_ip"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="right"
android:textSize="10pt" />
</LinearLayout>
---------------------------------------------------------------------------------------------------------------------
public class ListView1 extends ListActivity{//继承的是ListActivity

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> map1 = new HashMap<String,String>();
HashMap<String,String> map2 = new HashMap<String,String>();
HashMap<String,String> map3 = new HashMap<String,String>();
map1.put("user_name","张三");
map1.put("user_ip", "第一名");
map2.put("user_name","李四");
map2.put("user_ip", "第二名");
map3.put("user_name","王五");
map3.put("user_ip", "第三名");
list.add(map1);
list.add(map2);
list.add(map3);
SimpleAdapter listAdapter = new SimpleAdapter(this,list,R.layout.simpleadapter2,
new String[]{"user_name","user_ip"},new int[]{R.id.user_name,R.id.user_ip});
setListAdapter(listAdapter);//调用ListActivity中的setListAdapter()方法设置显示ListView
}
}
----------------------------------------------------------------------------------------------------------------------
* 此为ListActivity和listView数据适配器 。方法中的第一参数为当前对象,第二个参数为
* 我们要映射成Mapd的List结构,第三个参数为每一行列表的布局(此处为一行显示两个listView)
* 第四个参数是一个字符串数组,并规定了顺序,第五个参数是依次把第四个参数的文本隐射到listView的布局中去
* 本适配器的格式也可为:(注意映射的顺序)
* setListAdapter(new SimpleAdapter(this,list,R.layout.simpleadapter2,
new String[]{"user_name","user_ip"},new int[]{R.id.user_name,R.id.user_ip});
=======================================================================================================================
第五个例子:通过ListView来显示电话本中信息。
先创建LinearLayout对象和ListView对象,LinearLayout用来显示ListView
然后通过ListAdapter将获得的电话本数据与ListView连接起来
接着将ListAdapter添加到ListView中
最后将ListView添加到Linearlayout中,让屏幕显示LinearLayout。
要处理ListView事件需要为其添加setOnItemSelectedListener监听以及setOnItemClickListener监听
例:
public class ListView2 extends Activity{
LinearLayout linearLayout;
ListView listView1;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
linearLayout = new LinearLayout(this);//创建LinearLayout布局对象----------------------------------------------------------在代码中创建LinearLayout

linearLayout.setOrientation(linearLayout.VERTICAL);//设置方向
linearLayout.setBackgroundColor(android.graphics.Color.BLUE);//设置背景色

listView1 = new ListView(this);//创建ListView对象
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
listView1.setBackgroundColor(Color.BLACK);

linearLayout.addView(listView1,param);//添加listView到linearlayout中去

setContentView(linearLayout);//设置显示LinearLayout布局
//获取数据库Phones的Cursor
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
startManagingCursor(cur);
//ListAdapter是ListView和后台数据的桥梁。
//SimpleCursorAdapter是把数据中查询到的结果映射到listView中

ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,//表示每一行的布局包含两个数据项
cur,//数据库的Cursor对象
new String[]{PhoneLookup.DISPLAY_NAME,PhoneLookup.NUMBER},//从数据库的NAME和NUMBER两列中取数据
new int[]{android.R.id.text1,android.R.id.text2});//与NAME和NUMBER对应的Views

listView1.setAdapter(adapter);//将adapter添加到listView中

//在ListView中当鼠标滚动时会触发setOnItemSelectedListener
listView1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){-------------------------------------------------为listView1的视图添加setOnItemSelectedListener监听

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {

DisplayToast("滚动到第"+Long.toString(arg0.getSelectedItemId())+"项");
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {

//没有选中
}
});
//在ListView中当点击时会触发setClickListener
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

DisplayToast("选中了第"+Integer.toString(arg2+1)+"项");//对于选中的项进行处理
}
});
}
protected void DisplayToast(String string) {
// TODO Auto-generated method stub
Toast.makeText(this, string,Toast.LENGTH_SHORT).show();//显示Toast
}
}
==========================================================================================================================
Android 中关于Cursor类的介绍
使用过 SQLite 数据库的童鞋对 Cursor 应该不陌生,如果你是搞.net 开发你大可以把Cursor理解成 Ado.net 中的数据集合。
  关于 Cursor 在你理解和使用 Android Cursor 的时候你必须先知道关于 Cursor 的几件事情:
Cursor 是每行的集合。
  使用 moveToFirst() 定位第一行。
  你必须知道每一列的名称。
 你必须知道每一列的数据类型。
  Cursor 是一个随机的数据源。
  所有的数据都是通过下标取得。

关于 Cursor 的重要方法:
close()关闭游标,释放资源
copyStringToBuffer(int columnIndex, CharArrayBuffer buffer)在缓冲区中检索请求的列的文本,将其存储
getColumnCount()返回所有列的总数
  getColumnIndex(String columnName)返回指定列的名称,如果不存在返回-1
getColumnIndexOrThrow(String columnName)从零开始返回指定列名称,如果不存在将抛出IllegalArgumentException 异常。
getColumnName(int columnIndex)从给定的索引返回列名
getColumnNames()返回一个字符串数组的列名
getCount()返回Cursor 中的行数
moveToFirst()移动光标到第一行
moveToLast()移动光标到最后一行
moveToNext()移动光标到下一行
moveToPosition(int position)移动光标到一个绝对的位置
moveToPrevious()移动光标到上一行
  下面来看看一小段代码:
  if (cur.moveToFirst() == false){
  //为空的Cursor
  return;
  }

  访问 Cursor 的下标获得其中的数据
  int nameColumnIndex = cur.getColumnIndex(People.NAME);
  String name = cur.getString(nameColumnIndex);
  现在让我们看看如何循环 Cursor 取出我们需要的数据
  while(cur.moveToNext()){
  //光标移动成功
//把数据取出
  }
  当cur.moveToNext() 为假时将跳出循环,即 Cursor 数据循环完毕。
  如果你喜欢用 for 循环而不想用While 循环可以使用Google 提供的几下方法:
  isBeforeFirst()返回游标是否指向之前第一行的位置
isAfterLast()返回游标是否指向第最后一行的位置
isClosed()如果返回 true 即表示该游戏标己关闭

  有了以上的方法,可以如此取出数据
  for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
  int nameColumn = cur.getColumnIndex(People.NAME);
  int phoneColumn = cur.getColumnIndex(People.NUMBER);
  String name = cur.getString(nameColumn);
  String phoneNumber = cur.getString(phoneColumn);
  }
在Android 查询数据是通过Cursor 类来实现的。
当我们使用 SQLiteDatabase.query()方法时,就会得到Cursor对象, Cursor所指向的就是每一条数据。
Cursor 位于 android.database.Cursor类,可见出它的设计是基于数据库服务产生的。
  另外,还有几个己知的子类,分别为:
  AbstractCursor
  AbstractWindowedCursor
  CrossProcessCursor
  CursorWrapper
  MatrixCursor
  MergeCursor
  MockCursor
  SQLiteCursor
  具体详细的使用方法和解释可以去参照API

Toast 是Android中一种快讯信息类
Toast的实现很简单只有一行代码“Toast.makeText(this,String,Toast.LENGTH_SHORT).show();”
下面为一个接受短信的例子,其中用到了Toast。
toast.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/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Toast示例"
android:textSize="15pt"
/>
<Button
android:id= "@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Toast"
/>
</LinearLayout>
--------------------------------------------------------------------------------------------------------------
public class Toast1 extends Activity{
public Button button1;
public TextView textView1;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.toast);
textView1 =(TextView)findViewById(R.id.textView1);
button1= (Button)findViewById(R.id.button1);
button1.setOnClickListener(new Button.OnClickListener(){---------------------Button监听器
@Override
public void onClick(View v) {
DisplayToast("短信在这里显示");
}
});
}
protected void DisplayToast(String string) {
Toast.makeText(this,string,Toast.LENGTH_SHORT).show();
}
}
----------------------------------------------------------------------------------------------------------------
public class SmsReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();//得到一个Bundle对象
Object messages[] = (Object[]) bundle.get("pdus");//调用Bundle类中的get()方法得到Object的对象数组
SmsMessage smsMessage[] = new SmsMessage[messages.length];//创建SmsMessage对象数组
for(int n = 0;n<messages.length;n++){
smsMessage[n]= SmsMessage.createFromPdu((byte[])messages[n]);//createFromPdu()此方法为SmsMessage类中的静态方法,其返回值为SmsMessage对象
}
//产生一个Toast 其中getMessageBody()为得到一个String类型的返回值
Toast toast = Toast.makeText(context,"短信内容"+smsMessage[0].getMessageBody(),Toast.LENGTH_LONG);------------Toast的使用
toast.setGravity(Gravity.TOP|Gravity.LEFT,0,200);//设置toast位置
toast.show();//显示toast
}
}
---------------------------------------------------------------------------------------------------------------------
本例中使用了短信的借口,必须在AndroidManifest.xml中声明其权限
<receiver android:name = ".SmsReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
=====================================================================================================================
Dialog 对话框
Android中实现对话框可以使用AlertDialog类,以及自己定义对话框。必要时还可以设置监听器。
本例在XML文件中自定义对话框 以及使用AlertDialog来创建对话框
dialog.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="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/username"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:text="账号"
android:gravity="left"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/username"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:scrollHorizontally="true"
android:autoText="false"
android:capitalize="characters"
android:gravity="fill_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:text="密码"
android:gravity="left"
android:textAppearance="?android:attr/textAppearanceSmall" />

<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:scrollHorizontally="true"
android:autoText="false"
android:capitalize="none"
android:gravity="fill_horizontal"
android:password="true"
android:textAppearance="?android:attr/textAppearanceInverse" />
</LinearLayout>

public class UserDialog_AlertDialog extends Activity{
ProgressDialog progressDialog;//创建一个对话框中的进度条

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.empty);//empty为一个空的布局文件
//另一种书写形式在下面有解释
Dialog dialog = new AlertDialog.Builder(UserDialog_AlertDialog.this)//通过AlertDialog创建对话框
.setTitle("登陆提示")//设置标题
.setMultiChoiceItems(new String[]{"第一章","第二章","第三章"}, null,null)//设置多选按钮
//.setMessage("这里需要登陆")//设置内容
.setPositiveButton("确定", new DialogInterface.OnClickListener() {//设置监听器
@Override
public void onClick(DialogInterface dialog, int which) {
//为”确定“添加监听事件 创建自定义的对话框
LayoutInflater inflater = LayoutInflater.from(UserDialog_AlertDialog.this);------------------------------------------LayoutInflater的运用
final View DialogView = inflater.inflate(R.layout.dialog, null);//得到自定义对话框

AlertDialog alertDialog = new AlertDialog.Builder(UserDialog_AlertDialog.this)
.setTitle("登陆框")
.setIcon(R.drawable.qq)//改变对话框图片
.setView(DialogView)//设置自定义的对话框的样式
.setPositiveButton("可以", new DialogInterface.OnClickListener() {//在自定义的对话框中创建监听器
@Override
public void onClick(DialogInterface dialog, int which) {
progressDialog =ProgressDialog.show(UserDialog_AlertDialog.this, "请等待", "正在为你连接....",true);
new Thread(){
public void run(){
try{
sleep(3000);
}catch(Exception e){
e.printStackTrace();
}finally{
progressDialog.dismiss();//登录结束取消progressDialog对话框
}
}
}.start();
}
})
.setNegativeButton("不行", new DialogInterface.OnClickListener() {//设置取消

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
UserDialog_AlertDialog.this.finish();
}
}).create();
alertDialog.show();
}
})//设置确定按钮
.setNeutralButton("退出", new DialogInterface.OnClickListener() {//创建退出按钮

@Override
public void onClick(DialogInterface dialog, int which) {
//UserDialog_AlertDialog.this.finish();//退出
AlertDialog.Builder builder1 = new AlertDialog.Builder(UserDialog_AlertDialog.this);
builder1.setTitle("单选框");//设置标题
builder1.setSingleChoiceItems(new String[]{"你好","他好","我也好"}, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog.Builder builder2 = new AlertDialog.Builder(UserDialog_AlertDialog.this);
builder2.setTitle("普通列表项");
builder2.setItems(new String[]{"我只是普通列表项","我从第一层的退出项来的"}, null);//设置普通列表项
builder2.create().show();//创建与显示
}
});
builder1.setIcon(R.drawable.image2);//设置图片
builder1.create().show();//创建与显示
}
}).create();
dialog.show();//显示对话框
}
}

另一种创建对话框的方法dialog()
protected void dialog() {
AlertDialog.Builder builder = new Builder(Main.this);
builder.setMessage("确认退出吗?");
builder.setTitle("提示");
builder.setPositiveButton("确认", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Main.this.finish();
}
});
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}

也可以在onKeyDown(int keyCode, KeyEvent event)方法中调用此方法
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
dialog();
}
return false;
}
=========================================================================================================================
ImageView 将一张图片显示在屏幕上,需要创建一个显示图片的对象,Android中这个对象就是ImageView.下面例中设计ImageView图片然后
再通过线程对其Alpha进行更改。
imageview_handler.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"
>
<ImageView
android:id= "@+id/imageView_handler"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id= "@+id/textView_handler"
android:layout_below="@id/imageView_handler"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

public class ImageView_Handler extends Activity{
public TextView textView_handler;
public ImageView imageView_handler;
public boolean flag= false;//线程是否执行标志位
Handler handler = new Handler();----------------------------------------------Handler的运用
public int image_alpha = 255;//ImageView的透明度
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.imageview_handler);
flag = true;//初始化线程标志位
imageView_handler = (ImageView)findViewById(R.id.imageView_handler);
textView_handler = (TextView)findViewById(R.id.textView_handler);

imageView_handler.setImageResource(R.drawable.ee);//设置imageView的图片资源也可在xml文件中如下书写
//android:src= "@drawable/ee"
imageView_handler.setAlpha(image_alpha);//设置图片的透明度
//创建一个线程来更新Alpha值
handler = new Handler(){//接受更新后的消息
public void handleMessage(Message msg){
super.handleMessage(msg);
imageView_handler.setAlpha(image_alpha);
textView_handler.setText("当前Alpha值为:"+Integer.toString(image_alpha));

imageView_handler.invalidate();//更新 此行代码是用来更新View的 。在这个例子中我不用效果是一样的为什么在这我要加上他呢?不懂
}
};
new Thread(new Runnable(){

@Override
public void run() {
while(flag){
try{
Thread.sleep(200);
updateAlpha();//更新Alpha值
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}).start();
}
protected void updateAlpha() {
if(image_alpha>0){
image_alpha-=10;
}else {
image_alpha =0;
flag = false;//线程停止更新
}
handler.sendMessage(handler.obtainMessage());//发送Alpha更新的消息
}
}
===================================================================================================================================
Gallery 拖动效果
gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

* BaseAdapter继承自Adapter为Android中用到基础数据适配器,主要用途是将一组数据传到ListView,
* Gallery,Spinner,GridView等UI显示组件,其中getView是将获取后的组件View返回给UI,如ListView每一行
* 中TextView,以及Gallery中的每个ImageView。BaseAdapter相当于数据源与UI中的桥梁

public class Gallery_Adapter extends BaseAdapter{//通过继承BaseAdapter来装载这些图片
private Context context;//定义context 后面有解释 具体意思不是很清楚?
private Integer[] tId={
R.drawable.t1,
R.drawable.t2,
R.drawable.t3,
R.drawable.t4,
R.drawable.t5,
R.drawable.t6,
R.drawable.t7,
R.drawable.t8,
R.drawable.t9,
R.drawable.t10,
R.drawable.t11,
R.drawable.t12,
};
//声明Gallery_Adapter
public Gallery_Adapter(Context context){//构造器
this.context=context;
}
@Override
public int getCount() {//获取图片的个数
// TODO Auto-generated method stub
return tId.length;
}
@Override
public Object getItem(int position) {//获取图片在数组中位置
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {//获取图片在数组中位置
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = new ImageView(context);-------------------------------ImageView对象在代码中实现
imageView.setImageResource(tId[position]);//给ImageView设置要显示的图片资源
imageView.setLayoutParams(new Gallery.LayoutParams(80,80));//设置布局图片以120*120显示
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);//设置显示比例类型
return imageView;//返回数据库中的imageView资源给UI
}
}
/*
* Context字面意思是上下文,位于framework package的android.content.Context中,其实该类
* 为LONG型,类似Win32中的Handle句柄。很多方法需要通过 Context才能识别调用者的实例:比如
* 说Toast的第一个参数就是Context,一般在Activity中我们直接用this代替,代表调用者的实例
* 为Activity,而到了一个button的onClick(View view)等方法时,我们用this时就会报错,所以
* 我们可能使用ActivityName.this来解决,主要原因是因为实现Context的类主要有Android特有
* 的几个模型,Activity以及Service。

Context提供了关于应用环境全局信息的接口。它是一个抽象类,它的执行被Android系统所提供。
它允许获取以应用为特征的资源和类型。同时启动应用级的操作,如启动Activity,broadcasting和
接收intents。
* */

public class Gallery_BaseAdapter extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
Gallery gallery = (Gallery)findViewById(R.id.gallery1);//获取Gallery对象

gallery.setAdapter(new Gallery_Adapter(this));//将Gallery_Adapter添加到Gallery对象中去
gallery.setBackgroundResource(R.drawable.bj);//设置Gallery背景

//设置监听事件
gallery.setOnItemClickListener(new OnItemClickListener() {--------------------------------------------------------Gallery监听器

@Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(Gallery_BaseAdapter.this, "你选择了"+(position+1)+"号图片", Toast.LENGTH_LONG)
.show();
}
});
}
}
==========================================================================================================================
ImageSwitcher 切换图片
ImageSwitcher类必须设置一个ViewFactory,主要用来将显示的图片和父窗口区分开,所有要实现ViewSwitcher.ViewFactory接口,通过makeView()
方法来显示图片,这里会返回一个ImageView对象,在通过setImageResource用来显示指定的图片资源。

public class ImageSwitch_LinearLayout extends Activity implements ViewFactory, OnClickListener{
private static final int BUTTON_DWON_ID = 1;//下一页按钮ID 注意此处数组1,2,3我是随便取的此处还不是很清楚
private static final int BUTTON_UP_ID = 2;//上一页按钮ID
private static final int SWITCH_ID =3;//ImageSwitch对象的ID

private static int index = 0;//设置图片资源数组的索引
ImageSwitcher imageSwitcher;

private static final Integer[] integer ={//所要显示的图片资源数组
R.drawable.t1,
R.drawable.t2,
R.drawable.t3,
R.drawable.t4,
R.drawable.t5,
R.drawable.t6,
};
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

LinearLayout linearLayout = new LinearLayout(this);//创建一个线性布局
linearLayout.setOrientation(LinearLayout.VERTICAL);
imageSwitcher = new ImageSwitcher(this);//创建一个ImageSwitcher对象
linearLayout.addView(imageSwitcher);//在线性布局中添加imageSwitcher视图
imageSwitcher.setId(SWITCH_ID);//为ImageSwitcher对象设置Id
//为imageSwitcher对象设置数据源
imageSwitcher.setFactory(this);
imageSwitcher.setImageResource(integer[index]);
setContentView(linearLayout);//设置显示上面创建的线性布局

Button button1 = new Button(this);//创建上一页按钮
button1.setId(BUTTON_UP_ID);
button1.setText("上一页");
button1.setOnClickListener(this);//创立监听器
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100,100);//设置Button按钮的宽 ,高
params.gravity = Gravity.CENTER;//设置控件的相对屏幕的布局 ,不是控件中的文字相对控件的布局
linearLayout.addView(button1,params);//将button1 加入到线性布局中去

TextView textView1 = new TextView(this);
textView1.setId(BUTTON_DWON_ID);
textView1.setText("下一页");
textView1.setGravity(Gravity.CENTER);//设置文字权重
textView1.setBackgroundColor(Color.RED);
textView1.setTextColor(Color.BLUE);

textView1.setOnClickListener(this);
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(100,100);
params2.gravity = Gravity.CENTER;//设置控件的相对屏幕的布局 ,不是控件中的文字相对控件的布局
linearLayout.addView(textView1,params2);
}
@Override
public View makeView() {
// TODO Auto-generated method stub
return new ImageView(this);//将所有图片通过ImageView来显示
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch(view.getId()){
case BUTTON_UP_ID:
index ++;
if(index>=integer.length){
index = 0;
}
imageSwitcher.setImageResource(integer[index]);//用此方法显示指定图片
break;
case BUTTON_DWON_ID:
index --;
if(index<=0){
index = integer.length-1;
}
imageSwitcher.setImageResource(integer[index]);
break;
default:
break;
}
}

}
=======================================================================================================================
GridView 网格视图
当有多个元素要显示时,就需要使用BaseAdapter来存储。

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>

public class GridView_BaseAdapter extends BaseAdapter{

* BaseAdapter继承自Adapter为Android中用到基础数据适配器,主要用途是将一组数据传到ListView,
* Gallery,Spinner,GridView等UI显示组件,其中getView是将获取后的组件View返回给UI,如ListView每一行
* 中TextView,以及Gallery中的每个ImageView。BaseAdapter相当于数据源与UI中的桥梁

private Context context;//定义context 后面有解释 具体意思不是很清楚?
private Integer[] tId={
R.drawable.t1,
R.drawable.t2,
R.drawable.t3,
R.drawable.t4,
R.drawable.t5,
R.drawable.t6,
R.drawable.t7,
R.drawable.t8,

};
//声明Gallery_Adapter
public GridView_BaseAdapter(Context context){//构造器
this.context=context;
}
@Override
public int getCount() {//获取图片的个数
// TODO Auto-generated method stub
return tId.length;
}
@Override
public Object getItem(int position) {//获取图片在数组中位置
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {//获取图片在数组中位置
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView;
if(convertView ==null){//判断原来View是否为空 ,如果为空就创建 如果不为空就把原来的转为自己的View
imageView = new ImageView(context);

//注意:此行代码一加就会出现错误。原因是LayoutParams是对上一层控件的设置(即对父控件的设置),而此处ImageView已经是最上层控件了。
//imageView.setLayoutParams(new Gallery.LayoutParams(80,80));//设置布局图片以80*80显示
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);//设置显示比例类型
}else{
imageView = (ImageView)convertView;
}
imageView.setImageResource(tId[position]);//给ImageView设置资源
return imageView;//返回数据库中的imageView资源给UI
}
}

public class GridView_Adapter extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview_baseadapter);

GridView gridView12 = (GridView)findViewById(R.id.gridview1);
gridView12.setAdapter(new GridView_BaseAdapter(this));//添加元素到gridView中去
gridView12.setBackgroundResource(R.drawable.yj);//设置Gallery背景色

gridView12.setOnItemClickListener(new OnItemClickListener(){-----------------------------------------------------------GridView监听器

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3){
// TODO Auto-generated method stub
Toast.makeText(GridView_Adapter.this, "你选择了"+arg2+"号图片按钮",Toast.LENGTH_LONG ).show();
}
});
}
}
====================================================================================================================================================
ScrollView 卷轴视图
是指当拥有的很多内容,一屏显示不完时,需要通过滚动来显示视图。(如文字过长时)。下面这个例子当我们点击Button时自动产生多个类似项,如果一屏显示不完,则
通过ScrollView来显示。
scrollview.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:id="@+id/linearLayout_ScrollView"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView0"/>
<Button
android:id="@+id/button_ScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button0"/>
</LinearLayout>
</ScrollView>

* 问题:下面注释掉的部分没理解 注释掉得部分是为了实现循环滚动 ,但出现了问题?
* ScrollView是在屏幕显示不下的时候出现滚动条,但注意不要在ScrollView中放多个组件,否则会出现
* ERROR/AndroidRuntime(271): Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child
* (ScrollView只能包裹一个直接子元素)

public class Scroll_View extends Activity{
public ScrollView scrollView1;
public LinearLayout linearLayout_ScrollView;
public Button button01;
public Handler handler = new Handler();//使用Handler来更新布局高度,即跳转到新增的控件中去

public int index = 1;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.scrollview);
scrollView1 = (ScrollView)findViewById(R.id.scrollView1);
linearLayout_ScrollView = (LinearLayout)findViewById(R.id.linearLayout_ScrollView);
button01 = (Button)findViewById(R.id.button_ScrollView);

//设置监听器
button01.setOnClickListener(button02);
//button01.setOnKeyListener(N);//改变默认焦点
}
public Button.OnClickListener button02 = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText editText = new EditText(Scroll_View.this);
editText.setText("NI HAO"+index++);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout_ScrollView.addView(editText,params);

//editText.setOnKeyListener(M);//设置监听,改名默认焦点切换
handler.post(msg);//投递一个消息
}
};
public Runnable msg = new Runnable(){------------------------------------------------------------------------Runnable的使用
public void run(){
//此处作用是是屏幕跳到新加的一行当中去
//例如:如果新加一个EditText,运行效果就向上滚动一个EditText的宽度,如果超出整
//个屏幕N个EditText 就理解为屏幕最下方显示新增加的第N+1个EditText 依次向上为N,N-1
//N-2,N-3。而原来的第一个已不可见
int off = linearLayout_ScrollView.getMeasuredHeight()-scrollView1.getHeight();
if(off>0){
scrollView1.scrollTo(0,off);
}
}
};
//public View.OnKeyListener M = new View.OnKeyListener() {//事件监听
//
//@Override
//public boolean onKey(View v, int keyCode, KeyEvent event) {
TODO Auto-generated method stub
//if(keyCode ==KeyEvent.KEYCODE_DPAD_DOWN&&
//event.getAction() == KeyEvent.ACTION_DOWN&&
//v == linearLayout_ScrollView.getChildAt(linearLayout_ScrollView.getChildCount()-1)){
//findViewById(R.id.button1).requestFocus();
//}
//return false;
//}
//};
//public View.OnKeyListener N = new View.OnKeyListener() {
//
//@Override
//public boolean onKey(View v, int keyCode, KeyEvent event) {
TODO Auto-generated method stub
//View view = null;
//if(event.getAction()== KeyEvent.ACTION_DOWN){
//int A = linearLayout_ScrollView.getChildCount();
//switch(keyCode){
//case KeyEvent.KEYCODE_DPAD_UP:
//if(A>0){
//view = linearLayout_ScrollView.getChildAt(A-1);
//}
//break;
//case KeyEvent.KEYCODE_DPAD_DOWN:
//if(A<linearLayout_ScrollView.getWeightSum()){
//view = linearLayout_ScrollView.getChildAt(A);
//}
//break;
//default:
//break;
//}
//}
//if(view !=null){
//view.requestFocus();
//return true;
//}else{
//return false;
//}
//}
//};
}
=======================================================================================================================================
ProgressBar 进度条
progressbar.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"
>
<Button
android:id="@+id/button_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开progressbar"
/>
<ProgressBar
android:id="@+id/progressbar01"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:visibility="gone"
style="?android:attr/progressBarStyleHorizontal"//长形进度条
/>
<ProgressBar
android:id="@+id/progressbar02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:secondaryProgress="70"
android:progress="50"
android:visibility="gone"
style="?android:attr/progressBarStyleLarge"//圆形进度条
/>
</LinearLayout>

* 本例有一个问题如何使标题栏中的进度条在走完后 变为不可现?
public class ProgressBar_Handler extends Activity{
public ProgressBar progressbar01;
public ProgressBar progressbar02;
public Button button_bar;

public int count = 0;
public static final int STOP = 0;
public static final int CURRENT = 1;

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_PROGRESS);//设置窗口模式,因为需要显示进度条在标题栏
setProgressBarVisibility(true);

setContentView(R.layout.progressbar);

progressbar01 = (ProgressBar)findViewById(R.id.progressbar01);
progressbar02 = (ProgressBar)findViewById(R.id.progressbar02);
button_bar = (Button)findViewById(R.id.button_bar);

progressbar01.setIndeterminate(false);
progressbar02.setIndeterminate(false);

button_bar.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

progressbar01.setVisibility(View.VISIBLE);//设为可见状态
progressbar02.setVisibility(View.VISIBLE);

progressbar01.setMax(100);//设置最大值

progressbar01.setProgress(0);//设置当前值
progressbar02.setProgress(0);
progressbar01.setSecondaryProgress(80);//设置第二进度值

new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<200;i++){
try{
count = i*1;
Thread.sleep(10);
if(i==98){
Message m = new Message();
m.what = ProgressBar_Handler.STOP;
ProgressBar_Handler.this.handler.sendMessage(m);
}else{
Message m = new Message();-----------------------------------------------------------------更新进度条的方法
m.what = ProgressBar_Handler.CURRENT;
ProgressBar_Handler.this.handler.sendMessage(m);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}).start();
}});
}
Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case ProgressBar_Handler.STOP:
progressbar01.setVisibility(View.GONE);
progressbar02.setVisibility(View.GONE);
//setVisible(false);
Thread.currentThread().interrupt();
break;
case ProgressBar_Handler.CURRENT:
if(!Thread.currentThread().isInterrupted()){
progressbar01.setProgress(count);
progressbar01.setSecondaryProgress(count+20);
progressbar02.setProgress(count);

setProgress(count*100);//设置标题栏中前面的一个进度条进度值
setSecondaryProgress(count*100+30);//设置标题栏中后面的一个进度条进度值
}
break;
}
super.handleMessage(msg);
}
};
}
========================================================================================================================================
SeekBar 拖动条
作用:如音量调节等。要实现监听就需要实现SeekBar.OnSeekChangeListener接口。在SeekBar中需要监听3个事件,他们是:
在变化(onProgressChanged)在此可得到当前数值
开始拖动(onStartTrackingTouch),
停止拖动(onStopTrackingTouch)。
seekBar.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"
>
<SeekBar
android:id= "@+id/seekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
android:secondaryProgress="75"
/>
<TextView
android:id="@+id/textView1_SeekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textView2_SeekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="共选"
/>
</LinearLayout>

public class SeekBar1 extends Activity implements OnSeekBarChangeListener{
public SeekBar seekBar;
public TextView textView1_SeekBar;
public TextView textView2_SeekBar;

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.seekbar);
seekBar = (SeekBar)findViewById(R.id.seekBar);
textView1_SeekBar = (TextView)findViewById(R.id.textView1_SeekBar);
textView2_SeekBar = (TextView)findViewById(R.id.textView2_SeekBar);

seekBar.setOnSeekBarChangeListener(this);//为seekBar设置监听器--------------------------------------------------------SeekBar监听器
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,//位置改变
boolean fromUser) {
// TODO Auto-generated method stub
textView1_SeekBar.setText("当前值"+progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {//开始拖到
// TODO Auto-generated method stub
textView2_SeekBar.setText("正在调解");
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {//停止拖动
// TODO Auto-generated method stub
textView2_SeekBar.setText("停止调解");
}
}
=====================================================================================================================================================
Notification和NoticationManager状态栏提示
当有未接电话,或电话时,在Android状态栏中就会出现一个小图标,如果下拉状态栏就可以展开看到快讯通知。下面这个例子需要俩个Activity。
notification1_manager.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/textView_Manager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是怎么出来的?我是Notification_Manager"
/>
</LinearLayout>

notification2_manager.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"
>
<Button
android:id="@+id/button1_notification"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="通知_发出默认声音"
/>
<Button
android:id="@+id/button2_notification"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="通知_发出震动"
/>
<Button
android:id="@+id/button3_notification"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="通知_屏幕发亮"
/>
<Button
android:id="@+id/button4_notification"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="通知_发出声音,发亮,震动"
/>
</LinearLayout>

public class Notification_Manager extends Activity{
public TextView textView_manager;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.notification1_manager);
textView_manager =(TextView)findViewById(R.id.textView_Manager);

textView_manager.setOnClickListener(new TextView.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(Notification_Manager.this, Notification2_Manager.class);
startActivity(intent);
Notification_Manager.this.finish();
}
});
}
}

public class Notification2_Manager extends Activity{
public Button button1_notification,
button2_notification,
button3_notification,
button4_notification;
NotificationManager notificationManager;//声明通知消息管理器 Android系统提供NotificationManager来管理状态栏消息,
Intent intent;
PendingIntent pendingIntent;
Notification notification; //Android系统提供Notification来处理这些快讯信息,可以对Notification的内容,图标,标题等进行设置

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.notification2_manager);
//初始化notification对象
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);//通过getSystemService来获得NotficationManger对象
//构造Notification对象
notification = new Notification();

button1_notification =(Button)findViewById(R.id.button1_notification);
button2_notification =(Button)findViewById(R.id.button2_notification);
button3_notification =(Button)findViewById(R.id.button3_notification);
button4_notification =(Button)findViewById(R.id.button4_notification);

intent = new Intent(Notification2_Manager.this,Notification_Manager.class);//点击通知转移内容
//设置点击通知时显示内容的类。Penging中文意思就是:待定,将来发生或来临。
//PendingIntent不是像Intent那样立即发生,而是在合适的时候才会去触发对应的 Intent
pendingIntent = PendingIntent.getActivity(Notification2_Manager.this,0,intent, 0);

button1_notification.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notification.icon =R.drawable.qq;//设置通知在状态栏的图标
notification.tickerText ="我是QQ";//当我们点击通知时显示的内容

notification.defaults =notification.DEFAULT_SOUND;//通知发出默认的声音

//设置通知显示的参数(这两参数下拉可以看见)
notification.setLatestEventInfo(Notification2_Manager.this,"发出默认的声音","声音",pendingIntent);
notificationManager.notify(0,notification);//可以理解执行这个通知
}});
button2_notification.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notification.icon =R.drawable.qq;//设置通知在状态栏的图标
notification.tickerText ="我是QQ";//当我们点击通知时显示的内容

notification.defaults =notification.DEFAULT_VIBRATE;//通知发出震动

//设置通知显示的参数(这两参数下拉可以看见)
notification.setLatestEventInfo(Notification2_Manager.this,"发出震动","震动",pendingIntent);
notificationManager.notify(0,notification);//通过notify来执行Notification快讯,可以理解执行这个通知。
}});
button3_notification.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notification.icon =R.drawable.qq;//设置通知在状态栏的图标
notification.tickerText ="我是QQ";//当我们点击通知时显示的内容

notification.defaults =notification.DEFAULT_LIGHTS;//通知时屏幕发亮

//设置通知显示的参数(这两参数下拉可以看见)
notification.setLatestEventInfo(Notification2_Manager.this,"屏幕发亮","发亮",pendingIntent);
notificationManager.notify(0,notification);//可以理解执行这个通知
}});
button4_notification.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notification.icon =R.drawable.qq;//设置通知在状态栏的图标
notification.tickerText ="我是QQ";//当我们点击通知时显示的内容

notification.defaults =notification.DEFAULT_ALL;//通知发出默认的声音,发亮,震动

//设置通知显示的参数(这两参数下拉可以看见)
notification.setLatestEventInfo(Notification2_Manager.this,"声音,发亮,震动","3者都有",pendingIntent);
notificationManager.notify(0,notification);//可以理解执行这个通知
}});
}
}
======================================================================================================================================
ProgressDialog 对话框中的进度条的
可以通过如下方法对PogressDialog进行设置
setProgressDialog //设置进度条风格
setTitle: //设置标题
setMessage //设置提示信息
setIcon //设置标题图标
setIndeterminate//设置进度条是否不明确
setCancelable //设置是否可以按退回按键取消
setButton //设置一个Button需要监听Button事件
show //显示进度条

progressdialog.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:padding="10dp"
>
<Button
android:id="@+id/button1_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="长形进度条"
/>
<Button
android:id="@+id/button2_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="圆形进度条"
/>
</LinearLayout>

public class Progress_Dialog extends Activity{
public Button button1_Dialog;
public Button button2_Dialog;
ProgressDialog progressDialog;//声明进度条对话框
private int count;

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.progressdialog);
button1_Dialog = (Button)findViewById(R.id.button1_dialog);
button2_Dialog = (Button)findViewById(R.id.button2_dialog);

button1_Dialog.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//创建ProgressDialog对象
progressDialog = new ProgressDialog(Progress_Dialog.this);
//设置进度长形进度条风格
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//设置进度条标题
progressDialog.setTitle("长形进度条");
//设置提示信息
progressDialog.setMessage("如何改变其图片与形式");
//设置标题图标
progressDialog.setIcon(R.drawable.qq);
//设置进度条是否明确
progressDialog.setIndeterminate(false);
//设置是否可以按退出按键取消
progressDialog.setCancelable(true);
//设置进度条的一个Button按钮
progressDialog.setButton("确定", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();//点击确定按钮取消对话框
}
});
//显示进度条
progressDialog.show();
}});
button2_Dialog.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//创建ProgressDialog对象
progressDialog = new ProgressDialog(Progress_Dialog.this);
//设置进度条风格
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//设置进度条标题
progressDialog.setTitle("圆形进度条");
//设置提示信息
progressDialog.setMessage("如何改变其图片与形式");
//设置标题图标
progressDialog.setIcon(R.drawable.qq);
//设置进度条是否明确
progressDialog.setIndeterminate(false);
//设置是否可以按退出按键取消
progressDialog.setCancelable(true);
//设置进度条的一个Button按钮
progressDialog.setButton("确定", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();//点击确定按钮取消对话框
}
});
//显示进度条
progressDialog.show();
new Thread(){
public void run(){
try{
while(count <=100){
progressDialog.setProgress(count++);//由线程来控制进度值
Thread.sleep(100);
}
progressDialog.cancel();
}catch(InterruptedException e){
progressDialog.cancel();
}
}
}.start();
}});
}
}
==================================================================================================================================================
3.3 LayoutInflater
layoutinflater.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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ShowCustomDialog"
/>
</LinearLayout>

layoutinflater2.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:padding="10dp"
>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>

public class LayoutInflaterDemo extends Activity implements OnClickListener {

private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutinflater);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(this); //添加监听器
}
@Override
public void onClick(View v) {
showCustomDialog();
}
public void showCustomDialog(){
AlertDialog.Builder builder;
AlertDialog alertDialog;
Context mContext = LayoutInflaterDemo.this;

LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.layoutinflater2,null);

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, 我的名字叫QQ!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.qq);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show();
}
}

* LayoutInflater的使用,在实际开发种LayoutInflater这个类还是非常有用的,
* 它的作用类似于 findViewById(),不同点是LayoutInflater是用来找layout下
* xml布局文件,并且实例化!而findViewById()是找具体xml下的具体 widget控
* 件(如:Button,TextView等)。
* 例如:
public class LayoutInflaterActivity extends Activity {
private EditText et;
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 第一种方法
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.main, null);
// 第二种方法
// LayoutInflater inflater = getLayoutInflater();
// View layout = inflater.inflate(R.layout.main, null);
// 第三种方法
// LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
// View layout = inflater.inflate(R.layout.main, null);
// 这里是通过事先获得的布局文件来实例化具体控件,并且可以根据情况自定义控件
et = (EditText) layout.findViewById(R.id.edittext);
et.setBackgroundColor(Color.YELLOW);
btn = (Button) layout.findViewById(R.id.btn);
btn.setBackgroundColor(Color.CYAN);
// 显示
setContentView(layout);
}
}
另外补充下,getSystemService是Activity中的方法,根据传入的name来取得对应的服务对象,这些服务名称参数都是Context类中的常量:
传入的Name 返回的对象 说明
WINDOW_SERVICE WindowManager 管理打开的窗口程序
LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml里定义的view
ACTIVITY_SERVICE ActivityManager 管理应用程序的系统状态
POWER_SERVICE PowerManger 电源的服务
ALARM_SERVICE AlarmManager 闹钟的服务
NOTIFICATION_SERVICE NotificationManager 状态栏的服务
KEYGUARD_SERVICE KeyguardManager 键盘锁的服务
LOCATION_SERVICE LocationManager 位置的服务,如GPS
SEARCH_SERVICE SearchManager 搜索的服务
VEBRATOR_SERVICE Vebrator 手机震动的服务
CONNECTIVITY_SERVICE Connectivity 网络连接的服务
WIFI_SERVICE WifiManager Wi-Fi服务
TELEPHONY_SERVICE TeleponyManager 电话服务
======================================================================================================================================
3.4 界面布局
LinearLayout 线性布局 但一行(列)只能放一个控件
android:orientation="vertical"//垂直线性布局
android:orientation="horizontal"//水平线性布局
android:layout_weight="1"//控件权重,即占屏幕的比例 默认为0

RelativeLayout 相对布局
其参数有:Width,Height,Below,AlignTop,Toleft,Padding,MarginLeft注意其值都是相对其他元素来说的。
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:layout_below="@id/ok"
android:layout_marginLeft="10dip"
android:layout_alignParentRight="true"

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请输入:"/>
<View----------------------------------------------------------------------------View在xml文件中的运用
android:layout_height="2dip"
android:background="#FF909090" />
</RelativeLayout>

TableLayout 表单布局
TableLayout容器不会显示Row,Column,Cell的边框线。
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow>
<TextView
android:id= "@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button,TextView,EditView"
/>
<TextView
android:id ="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SimpleAdapter"
android:gravity="right"
/>
</TableRow>
</TableLayout>

FrameLayout 里面只可以有一个控件,且此不能设置此控件位置,此控件总是位于左上角

AbsoluteLayout 里面可以放多个控件,可以定义自己控件的x,y

TabWidget 切换卡 通过继承TabActivity来实现。TabHost 是一个用来存放多个Tab标签的容器,要使用TabHost,要通过getTabHost方法来获得TabHost对象,然后通过addTab方法来向
TabHost中添加Tab.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is a tab" />
<TextView
android:id="@+id/textview2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is another tab" />
<TextView
android:id="@+id/textview3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is a third tab" />
</FrameLayout>
</LinearLayout>
</TabHost>

public class Activity01 extends TabActivity{
//声明TabHost对象
TabHost mTabHost;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//取得TabHost对象
mTabHost = getTabHost();
/* 为TabHost添加标签 */
mTabHost.addTab(mTabHost.newTabSpec("tab_test1")//新建一个newTabSpec(newTabSpec)
.setIndicator("TAB 1",getResources().getDrawable(R.drawable.img1))//设置其标签和图标(setIndicator)
.setContent(R.id.textview1));//设置内容(setContent)
mTabHost.addTab(mTabHost.newTabSpec("tab_test2")
.setIndicator("TAB 2",getResources().getDrawable(R.drawable.img2))
.setContent(R.id.textview2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3")
.setIndicator("TAB 3",getResources().getDrawable(R.drawable.img3))
.setContent(R.id.textview3));

mTabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));//设置TabHost的背景颜色
//mTabHost.setBackgroundResource(R.drawable.bg0);//设置TabHost的背景图片资源

mTabHost.setCurrentTab(0); //设置当前显示哪一个标签

mTabHost.setOnTabChangedListener(new OnTabChangeListener(){ //标签切换事件处理,setOnTabChangedListener -------------------------------------------TabWidget监听器

@Override
public void onTabChanged(String tabId){
Dialog dialog = new AlertDialog.Builder(Activity01.this)
.setTitle("提示")
.setMessage("当前选中:"+tabId+"标签")
.setPositiveButton("确定",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton){
dialog.cancel();
}
}).create();//创建按钮
dialog.show();
}
});
}
}














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值