android 资料收集大全

1. android帧动画

目录结构

第一步

frame.ani.xml

第二步

anim.xml

第三步

AnimActivity.java

第四步

AndroidManifest.xml

2. android补间动画

分类: android入门2011-03-25 00:27102人阅读评论(0)收藏举报

目录结构

第一步

anim/tween_anim.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <set xmlns:android="http://schemas.android.com/apk/res/android">

3. <alpha

4. android:fromAlpha="0.0"

5. android:toAlpha="1.0"

6. android:duration="6000"/>

7. <scale

8. android:interpolator="@android:anim/accelerate_decelerate_interpolator"

9. android:fromXScale="0.0" android:toXScale="1.0"

10. android:fromYScale="0.0" android:toYScale="1.0"

11. android:pivotX="50%" android:pivotY="50%"

12. android:fillAfter="false"

13. android:duration="9000"/>

14. <translate

15. android:fromXDelta="30" android:toXDelta="0"

16. android:fromYDelta="30" android:toYDelta="0"

17. android:duration="10000"/>

18. <rotate

19. android:interpolator="@android:anim/accelerate_decelerate_interpolator"

20. android:fromDegrees="0" android:toDegrees="+360"

21. android:pivotX="50%" android:pivotY="50%"

22. android:duration="10000"/>

23. </set>

第二步

layout/tween_anim.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <LinearLayout

3. xmlns:android="http://schemas.android.com/apk/res/android"

4. android:orientation="vertical"

5. android:layout_width="fill_parent"

6. android:layout_height="fill_parent">

7. <ImageView

8. android:id="@+id/iv"

9. android:src="@drawable/p1"

10. android:layout_width="wrap_content" android:layout_height="wrap_content"

11. android:layout_gravity="center_horizontal"

12. />

13. <Button

14. android:id="@+id/btn"

15. android:text="Click"

16. android:layout_width="fill_parent"

17. android:layout_height="wrap_content"

18. />

19. </LinearLayout>

第三步

TweenAnimActivity.java

view plaincopy to clipboardprint?

1. package com.skytao;

2.

3. import android.app.Activity;

4. import android.os.Bundle;

5. import android.view.View;

6. import android.view.View.OnClickListener;

7. import android.view.animation.Animation;

8. import android.view.animation.AnimationUtils;

9. import android.widget.Button;

10. import android.widget.ImageView;

11.

12. public class TweenAnimActivity extends Activity {

13.

14. public void onCreate(Bundle savedInstanceState) {

15. super.onCreate(savedInstanceState);

16. setContentView(R.layout.tween_anim);

17. Button btn = (Button) findViewById(R.id.btn);

18. btn.setOnClickListener(new OnClickListener() {

19.

20. @Override

21. public void onClick(View v) {

22. ImageView iv = (ImageView) findViewById(R.id.iv);

23. Animation animation =

24. AnimationUtils.loadAnimation(TweenAnimActivity.this,

25. R.anim.tween_ani);

26. iv.startAnimation(animation);

27. }

28. });

29. }

30. }

3. android 自动完成文本框

目录结构

第一步

auto_complete_text.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <LinearLayout

3. xmlns:android="http://schemas.android.com/apk/res/android"

4. android:layout_width="fill_parent"

5. android:layout_height="fill_parent">

6. <AutoCompleteTextView

7. android:id="@+id/myAutoCompleteTextView"

8. android:layout_width="fill_parent"

9. android:layout_height="wrap_content" />

10. </LinearLayout>

第二步

MainActivity.java

view plaincopy to clipboardprint?

1. package com.taofu5;

2.

3. import com.taofu5.R;

4.

5. import android.app.Activity;

6. import android.os.Bundle;

7. import android.widget.ArrayAdapter;

8. import android.widget.AutoCompleteTextView;

9.

10. public class MainActivity extends Activity {

11.

12. private static final String[] myStr = {"aaa","bbb","ccc","aabb","aad"};

13. @Override

14. public void onCreate(Bundle savedInstanceState) {

15. super.onCreate(savedInstanceState);

16. setContentView(R.layout.auto_complete_text);

17. ArrayAdapter<String> aa =

18. new ArrayAdapter<String>(this,

19. android.R.layout.simple_dropdown_item_1line,myStr) {

20. };

21. AutoCompleteTextView textView =

22. (AutoCompleteTextView) findViewById(R.id.myAutoCompleteTextView);

23. textView.setAdapter(aa);

24. textView.setThreshold(1);

25. }

26. }

第三步

AndroidManifest.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

3. package="com.taofu5"

4. android:versionCode="1"

5. android:versionName="1.0">

6. <application android:icon="@drawable/icon" android:label="@string/app_name">

7. <activity android:name=".MainActivity"

8. android:label="@string/app_name">

9. <intent-filter>

10. <action android:name="android.intent.action.MAIN" />

11. <category android:name="android.intent.category.LAUNCHER" />

12. </intent-filter>

13. </activity>

14.

15. </application>

16. <uses-sdk android:minSdkVersion="7" />

17.

18. </manifest>

效果图如下:

That's all.

分享到:

· 上一篇:2. android补间动画

· 下一篇:4. android 滚动视图

4. android 滚动视图

目录结构

第一步:

ScrollViewActivity.java

view plaincopy to clipboardprint?

1. package com.taofu5;

2.

3. import android.app.Activity;

4. import android.os.Bundle;

5. import android.widget.ScrollView;

6. import android.widget.TextView;

7.

8. public class ScrollViewActivity extends Activity {

9.

10. ScrollView scrollView;

11.

12. String msg = "滚动视图,滚动视图演示滚动视图,滚动视图演示滚动视图";

13.

14. String str = "";

15. public void onCreate(Bundle savedInstanceState) {

16. super.onCreate(savedInstanceState);

17.

18. scrollView = new ScrollView(this);

19. TextView tv = new TextView(this);

20. tv.setTextSize(23);

21. for(int i=0; i<20; i++) {

22. str = str + msg;

23. }

24. tv.setText(str);

25. scrollView.addView(tv);

26. setContentView(scrollView);

27. }

28. }

第二步

AndroidManifest.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

3. package="com.taofu5"

4. android:versionCode="1"

5. android:versionName="1.0">

6. <application android:icon="@drawable/icon" android:label="@string/app_name">

7. <activity android:name=".ScrollViewActivity"

8. android:label="@string/app_name">

9. <intent-filter>

10. <action android:name="android.intent.action.MAIN" />

11. <category android:name="android.intent.category.LAUNCHER" />

12. </intent-filter>

13. </activity>

14.

15. </application>

16. <uses-sdk android:minSdkVersion="7" />

17.

18. </manifest>

效果如下:

分享到:

· 上一篇:3. android 自动完成文本框

· 下一篇:最简单的网络爬虫(用到了htmlparser,httpClient)

5. android 列表视图

分类: android入门2011-04-01 00:37166人阅读评论(0)收藏举报

目录结构

第一步

value/strings.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <resources>

3. <string name="hello">你选择了</string>

4. <string name="app_name">高级控件</string>

5. <string name="andy">Andy Rubin /nAndroid的创造者</string>

6. <string name="bill">Bill Joy /nJava的创造者</string>

7. <string name="edgar">Edgar F. Codd /n关系数据库之父</string>

8. <string name="torvalds">Linus Torvalds /nLinux之父</string>

9. <string name="turing">Turing Alan /nIT的祖师爷</string>

10. <string name="ys">你选择了</string>

11. </resources>

第二步

value/colors.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <resources>

3. <color name="red">#fd8d8d</color>

4. <color name="green">#9cfda3</color>

5. <color name="blue">#8d9dfd</color>

6. <color name="white">#FFFFFF</color>

7. <color name="black">#000000</color>

8. <color name="gray">#050505</color>

9. </resources>

第三步

layout/list_view_layout.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <LinearLayout

3. xmlns:android="http://schemas.android.com/apk/res/android"

4. android:orientation="vertical"

5. android:layout_width="wrap_content"

6. android:layout_height="wrap_content">

7. <TextView android:id="@+id/textview"

8. android:layout_width="fill_parent"

9. android:layout_height="wrap_content"

10. android:textSize="24dip"

11. android:textColor="@color/white"

12. android:text="@string/hello" />

13. <ListView android:id="@+id/listview"

14. android:layout_width="fill_parent"

15. android:layout_height="wrap_content"/>

16. </LinearLayout>

第四步

ListViewActivity.java

view plaincopy to clipboardprint?

1. package com.taofu5;

2.

3. import android.app.Activity;

4. import android.os.Bundle;

5. import android.view.Gravity;

6. import android.view.View;

7. import android.view.ViewGroup;

8. import android.view.View.OnClickListener;

9. import android.widget.AdapterView;

10. import android.widget.BaseAdapter;

11. import android.widget.Gallery;

12. import android.widget.ImageView;

13. import android.widget.LinearLayout;

14. import android.widget.ListView;

15. import android.widget.TextView;

16. import android.widget.AdapterView.OnItemClickListener;

17. import android.widget.AdapterView.OnItemSelectedListener;

18.

19. public class ListViewActivity extends Activity {

20.

21. int[] msgIds = {R.string.andy,R.string.bill,

22. R.string.edgar, R.string.torvalds,R.string.turing};

23. int[] imgIds = {R.drawable.andy, R.drawable.bill,

24. R.drawable.edgar, R.drawable.torvalds, R.drawable.turing};

25.

26. public void onCreate(Bundle savedInstanceState) {

27. super.onCreate(savedInstanceState);

28. setContentView(R.layout.list_view_layout);

29.

30. ListView listView = (ListView) this.findViewById(R.id.listview);

31. BaseAdapter adapter = new BaseAdapter() {

32.

33. @Override

34. public int getCount() {

35. return imgIds.length;

36. }

37.

38. @Override

39. public Object getItem(int arg0) {

40. return null;

41. }

42.

43. @Override

44. public long getItemId(int arg0) {

45. return 0;

46. }

47.

48. @Override

49. public View getView(int num, View view, ViewGroup group) {

50. LinearLayout ll = new LinearLayout(ListViewActivity.this);

51. ll.setOrientation(LinearLayout.HORIZONTAL);

52. ll.setPadding(5, 5, 5, 5);

53.

54. ImageView imageView = new ImageView(ListViewActivity.this);

55. imageView.setImageDrawable(getResources().getDrawable(imgIds[num]));

56. imageView.setScaleType(ImageView.ScaleType.FIT_XY);

57. imageView.setLayoutParams(new Gallery.LayoutParams(100, 98));

58. ll.addView(imageView);

59.

60. TextView textView = new TextView(ListViewActivity.this);

61. textView.setText(getResources().getText(msgIds[num]));

62. textView.setTextSize(24);

63. textView.setTextColor(

64. ListViewActivity.this.getResources().getColor(R.color.blue));

65. textView.setPadding(5, 5, 5, 5);

66. textView.setGravity(Gravity.LEFT);

67. ll.addView(textView);

68.

69. return ll;

70. }

71.

72. };

73.

74. listView.setAdapter(adapter);

75.

76. listView.setOnItemSelectedListener(new OnItemSelectedListener() {

77.

78. @Override

79. public void onItemSelected(AdapterView<?> adapter, View view,

80. int num, long lnum) {

81. TextView textView = (TextView) findViewById(R.id.textview);

82. LinearLayout layout = (LinearLayout) view;

83. TextView subTextView = (TextView)layout.getChildAt(1);

84. StringBuilder strBuilder = new StringBuilder();

85. strBuilder.append(getResources().getText(R.string.ys));

86. strBuilder.append(":" + subTextView.getText());

87. String stemp = strBuilder.toString();

88. textView.setText(stemp.split("//n")[0]);

89. }

90.

91. @Override

92. public void onNothingSelected(AdapterView<?> arg0) {

93.

94. }

95.

96. });

97.

98. listView.setOnItemClickListener(new OnItemClickListener() {

99.

100. @Override

101. public void onItemClick(AdapterView<?> adapter, View view, int num,

102. long lnum) {

103. TextView textView = (TextView) findViewById(R.id.textview);

104. LinearLayout layout = (LinearLayout) view;

105. TextView subTextView = (TextView)layout.getChildAt(1);

106. StringBuilder strBuilder = new StringBuilder();

107. strBuilder.append(getResources().getText(R.string.ys));

108. strBuilder.append(":" + subTextView.getText());

109. String stemp = strBuilder.toString();

110. textView.setText(stemp.split("//n")[0]);

111. }

112.

113. });

114.

115. }

116. }

第五步:

AndroidManifest.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

3. package="com.taofu5"

4. android:versionCode="1"

5. android:versionName="1.0">

6. <application android:icon="@drawable/icon" android:label="@string/app_name">

7. <activity android:name=".ListViewActivity"

8. android:label="@string/app_name">

9. <intent-filter>

10. <action android:name="android.intent.action.MAIN" />

11. <category android:name="android.intent.category.LAUNCHER" />

12. </intent-filter>

13. </activity>

14.

15. </application>

16. <uses-sdk android:minSdkVersion="7" />

17.

18. </manifest>

效果截图如下

分享到:

· 上一篇:最简单的网络爬虫(用到了htmlparser,httpClient)

· 下一篇:6 android 滑块和进度条

6 android 滑块和进度条

分类: android入门2011-04-12 19:48192人阅读评论(0)收藏举报

目录结构

第一步:

layout/progress_bar_layout.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <LinearLayout

3. xmlns:android="http://schemas.android.com/apk/res/android"

4. android:orientation="vertical"

5. android:layout_width="fill_parent"

6. android:layout_height="fill_parent">

7. <ProgressBar android:id="@+id/prograssBar"

8. android:layout_width="fill_parent"

9. android:layout_height="wrap_content"

10. android:max="100"

11. android:progress="10"

12. style="@android:style/Widget.ProgressBar.Horizontal"

13. />

14. <SeekBar android:id="@+id/seekBar"

15. android:layout_width="fill_parent"

16. android:layout_height="wrap_content"

17. android:max="100"

18. android:progress="20"

19. />

20. </LinearLayout>

第二步:

src/com/taofu5/ProgressBarActivity.java

view plaincopy to clipboardprint?

1. package com.taofu5;

2.

3. import android.app.Activity;

4. import android.os.Bundle;

5. import android.widget.ProgressBar;

6. import android.widget.SeekBar;

7.

8. public class ProgressBarActivity extends Activity {

9.

10. public void onCreate(Bundle savedInstanceState) {

11. super.onCreate(savedInstanceState);

12. this.setContentView(R.layout.progress_bar_layout);

13.

14. SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);

15. seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

16.

17. @Override

18. public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

19. ProgressBar progressBar = (ProgressBar) findViewById(R.id.prograssBar);

20. progressBar.setProgress(seekBar.getProgress());

21. }

22.

23. @Override

24. public void onStopTrackingTouch(SeekBar seekBar) {}

25. @Override

26. public void onStartTrackingTouch(SeekBar seekBar) {}

27.

28. });

29. }

30. }

第三步:

AndroidManifest.xml

view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>

2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

3. package="com.taofu5"

4. android:versionCode="1"

5. android:versionName="1.0">

6. <application android:icon="@drawable/icon" android:label="@string/app_name">

7. <activity android:name=".ProgressBarActivity"

8. android:label="@string/app_name">

9. <intent-filter>

10. <action android:name="android.intent.action.MAIN" />

11. <category android:name="android.intent.category.LAUNCHER" />

12. </intent-filter>

13. </activity>

14.

15. </application>

16. <uses-sdk android:minSdkVersion="7" />

17. </manifest>

效果图:

分享到:

· 上一篇:5. android 列表视图

· 下一篇:7 android 星级滑块

7 android 星级滑块

分类: android入门2011-04-12 21:24175人阅读评论(1)收藏举报

目录结构

1、res/layout/rating_bar_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="wrap_content">

7.<ProgressBar android:id="@+id/progressBar"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:max="100"

11.android:progress="10"

12.style="@android:style/Widget.ProgressBar.Horizontal"mce_style="@android:style/Widget.ProgressBar.Horizontal"

13./>

14.<RatingBar android:id="@+id/ratingBar"

15.android:layout_width="wrap_content"

16.android:layout_height="wrap_content"

17.android:max="5"

18.android:rating="0.5"

19./>

20.</LinearLayout>

2、src/com/taofu5/RatingBarActivity.java

view plaincopy to clipboardprint?

1.packagecom.taofu5;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.importandroid.widget.ProgressBar;

6.importandroid.widget.RatingBar;

7.

8.publicclass RatingBarActivity extends Activity {

9.

10.publicvoid onCreate(Bundle savedInstanceState) {

11.super.onCreate(savedInstanceState);

12.this.setContentView(R.layout.rating_bar_layout);

13.

14.RatingBarratingBar = (RatingBar) findViewById(R.id.ratingBar);

15.ratingBar.setOnRatingBarChangeListener(newRatingBar.OnRatingBarChangeListener() {

16.

17.@Override

18.publicvoid onRatingChanged(RatingBar ratingBar, float progress, boolean fromUser) {

19.ProgressBarprogressBar = (ProgressBar) findViewById(R.id.progressBar);

20.progressBar.setProgress((int)(ratingBar.getRating()*100/5));

21.}

22.});

23.}

24.}

3、AndroidManifest.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3.package="com.taofu5"

4.android:versionCode="1"

5.android:versionName="1.0">

6.<application android:icon="@drawable/icon"android:label="@string/app_name">

7.<activity android:name=".RatingBarActivity"

8.android:label="@string/app_name">

9.<intent-filter>

10.<action android:name="android.intent.action.MAIN"/>

11.<category android:name="android.intent.category.LAUNCHER"/>

12.</intent-filter>

13.</activity>

14.

15.</application>

16.<uses-sdk android:minSdkVersion="7"/>

17.</manifest>

效果图:

分享到:

· 上一篇:6 android 滑块和进度条

· 下一篇:8. android Tab 选项卡控件

8. android Tab 选项卡控件

分类: android入门2011-04-14 22:48388人阅读评论(2)收藏举报

目录结构

第一步

res/values/strings.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string name="hello">Hello World, MyTabActivity!</string>

4.<string name="app_name">选项卡Demo</string>

5.<string name="andy">Andy Rubin--Android的创造者</string>

6.<string name="bill">Bill Joy--Java的创造者</string>

7.<string name="torvalds">Linus Torvalds --Linux之父</string>

8.</resources>

第二步

res/layout/tab_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<!--

3.FrameLayout:一个FrameLayout对象好比一块在屏幕上提前预定好的空白区域,

4.然后可以填充一些元素到里边,比方说一张图片等。

5.需要注意的是所有元素都被放置在FrameLayout区域的左上的区域,

6.而且无法为这些元素指定一个确切的位置。如果有多个元素,则后边的会重叠在前一个元素上。

7.

8.android:gravity用于设置View组件的对齐方式

9.(另外,android:layout_gravity用于设置Container组件的对齐方式)

10.center_horizontal不改变控件大小,对其到容器横向中间位置(也就是在竖直方向的中间)

11.

12.android:scaleType="fitXY" 把图片不按比例来扩大或者缩小显示

13.-->

14.<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

15.android:layout_width="fill_parent"

16.android:layout_height="fill_parent">

17.<LinearLayout android:id="@+id/linearLayout1"

18.xmlns:android="http://schemas.android.com/apk/res/android"

19.android:layout_width="fill_parent"

20.android:layout_height="fill_parent"

21.android:gravity="center_horizontal"

22.android:orientation="vertical"

23.>

24.<ImageView

25.android:id="@+id/imageView01"

26.android:layout_gravity="center"

27.android:scaleType="fitXY"

28.android:layout_width="wrap_content"

29.android:layout_height="wrap_content"

30.android:src="@drawable/andy"/>

31.<TextView

32.android:id="@+id/testView01"

33.android:layout_width="wrap_content"

34.android:layout_height="wrap_content"

35.android:textSize="20dip"

36.android:text="@string/andy"

37./>

38.</LinearLayout>

39.

40.<LinearLayout android:id="@+id/linearLayout2"

41.xmlns:android="http://schemas.android.com/apk/res/android"

42.android:layout_width="fill_parent"

43.android:layout_height="fill_parent"

44.android:gravity="center_horizontal"

45.android:orientation="vertical"

46.>

47.<ImageView

48.android:id="@+id/imageView02"

49.android:layout_gravity="center"

50.android:scaleType="fitXY"

51.android:layout_width="wrap_content"

52.android:layout_height="wrap_content"

53.android:src="@drawable/bill"/>

54.<TextView

55.android:id="@+id/testView02"

56.android:layout_width="wrap_content"

57.android:layout_height="wrap_content"

58.android:textSize="20dip"

59.android:text="@string/bill"

60./>

61.</LinearLayout>

62.

63.<LinearLayout android:id="@+id/linearLayout3"

64.xmlns:android="http://schemas.android.com/apk/res/android"

65.android:layout_width="fill_parent"

66.android:layout_height="fill_parent"

67.android:gravity="center_horizontal"

68.android:orientation="vertical"

69.>

70.<ImageView

71.android:id="@+id/imageView03"

72.android:layout_gravity="center"

73.android:scaleType="fitXY"

74.android:layout_width="wrap_content"

75.android:layout_height="wrap_content"

76.android:src="@drawable/torvalds"/>

77.<TextView

78.android:id="@+id/testView03"

79.android:layout_width="wrap_content"

80.android:layout_height="wrap_content"

81.android:textSize="20dip"

82.android:text="@string/torvalds"

83./>

84.</LinearLayout>

85.</FrameLayout>

第三步

src/com/myandroid/tab/MyTabActivity.java

view plaincopy to clipboardprint?

1.packagecom.myandroid.tab;

2.

3.importandroid.app.TabActivity;

4.importandroid.os.Bundle;

5.importandroid.view.LayoutInflater;

6.importandroid.widget.TabHost;

7.

8.publicclass MyTabActivity extends TabActivity {

9.

10.publicvoid onCreate(Bundle savedInstanceState) {

11.super.onCreate(savedInstanceState);

12.TabHosttabHost = this.getTabHost();

13./*

14.*LayoutInflater的作用类似于findViewById(),

15.* 不同点是LayoutInflater是用来找layout文件夹下的xml布局文件,并且实例化

16.* 注:findViewById()只是找控件之类(如Button和EditView)

17.*

18.*LayoutInflater.from(this)获得context实例

19.* 也就是相当于this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

20.*LAYOUT_INFLATER_SERVICE 取得xml里定义的view

21.*-----------------------------------------------------------------------

22.*getSystemService:

23.* 根据传入的NAME来取得对应的Object,然后转换成相应的服务对象

24.* android的后台运行在很多service,

25.* 它们在系统启动时被SystemServer开启,支持系统的正常工作,

26.* 比如MountService监听是否有SD卡安装及移除,ClipboardService提供剪切板功能,

27.* 应用程序可以通过系统提供的Manager接口来访问这些Service提供的数据

28.*-----------------------------------------------------------------------

29.*

30.* inflate是把xml表述的layout转化为View

31.*tabHost.getTabContentView() 获得Tab标签页的FrameLayout

32.* true表示将inflate绑定到根布局元素上

33.*/

34.LayoutInflater.from(this)

35..inflate(R.layout.tab_layout,

36.tabHost.getTabContentView(),true);

37.

38./*

39.*tabHost.newTabSpec("Tab1") 创建TabHost.TabSpec,

40.* TabSpec即是选项卡的指示符,对于TabSpec可以设置一个标题或者设置一个标题和图标

41.*setIndicator 是为选项卡指示符指定一个标签和图标

42.*setContent 为选项卡的内容指定视图的ID

43.*/

44.tabHost.addTab(

45.tabHost.newTabSpec("Tab1")

46..setIndicator("Tab1",getResources().getDrawable(R.drawable.png1)

47.).setContent(R.id.linearLayout1)

48.);

49.tabHost.addTab(

50.tabHost.newTabSpec("Tab2")

51..setIndicator("Tab2",getResources().getDrawable(R.drawable.png2)

52.).setContent(R.id.linearLayout2)

53.);

54.tabHost.addTab(

55.tabHost.newTabSpec("Tab3")

56..setIndicator("Tab3",getResources().getDrawable(R.drawable.png3)

57.).setContent(R.id.linearLayout3)

58.);

59.}

60.

61.}

第四步

AndroidManifest.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3.package="com.myandroid.tab"

4.android:versionCode="1"

5.android:versionName="1.0">

6.<application android:icon="@drawable/icon"android:label="@string/app_name">

7.<activity android:name=".MyTabActivity"

8.android:label="@string/app_name">

9.<intent-filter>

10.<action android:name="android.intent.action.MAIN"/>

11.<category android:name="android.intent.category.LAUNCHER"/>

12.</intent-filter>

13.</activity>

14.

15.</application>

16.<uses-sdk android:minSdkVersion="8"/>

17.</manifest>

效果图:

源码地址:

http://download.csdn.net/source/3192235

分享到:

· 上一篇:7 android 星级滑块

· 下一篇:在Windows环境下,下载Android源代码(经过测试此方法仅能下载common,参考下载TortoiseGit办法)

9. android Gallery(画廊)以及BaseAdapter

分类: android入门2011-04-18 19:08507人阅读评论(3)收藏举报

目录结构

第一步:

/GalleryDemo/res/layout/gallery_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="wrap_content"

6.android:layout_height="wrap_content"

7.android:gravity="center_vertical"

8.android:layout_gravity="center">

9.<!--

10.android:unselectedAlpha设置选中的图片的透明度

11.android:spacing图片之间的空白大小

12.-->

13.<Gallery

14.android:id="@+id/gallery"

15.android:layout_width="fill_parent"

16.android:layout_height="fill_parent"

17.android:spacing="10dip"

18.android:unselectedAlpha="1" />

19.</LinearLayout>

第二步:

/GalleryDemo/src/com/mygallery/activity/GalleryActivity.java

view plaincopy to clipboardprint?

1.packagecom.mygallery.activity;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.importandroid.view.View;

6.importandroid.view.ViewGroup;

7.importandroid.widget.AdapterView;

8.importandroid.widget.BaseAdapter;

9.importandroid.widget.Gallery;

10.importandroid.widget.ImageView;

11.importandroid.widget.AdapterView.OnItemClickListener;

12.

13.publicclass GalleryActivity extends Activity {

14.

15.int[]imgIds = {R.drawable.a, R.drawable.b,

16.R.drawable.c,R.drawable.d, R.drawable.e};

17.@Override

18.publicvoid onCreate(Bundle savedInstanceState) {

19.super.onCreate(savedInstanceState);

20.setContentView(R.layout.gallery_layout);

21.

22.Gallerygallery = (Gallery) findViewById(R.id.gallery);

23.BaseAdapteradapter = new GalleryAdpter();

24.gallery.setAdapter(adapter);

25.OnItemClickListenerlistener = new OnItemClickListener() {

26.

27./*

28.* parent 发生点击动作的AdapterView

29.* view 在AdapterView中被点击的视图(它是由adapter提供的一个视图)

30.*position 视图在adapter中的位置

31.* id 被点击元素的行id

32.*/

33.@Override

34.publicvoid onItemClick(AdapterView<?> parent, View view, int position,

35.long id){

36.Gallerygallery = (Gallery) findViewById(R.id.gallery);

37.gallery.setSelection(position);

38.}

39.};

40.

41.gallery.setOnItemClickListener(listener);

42.}

43.

44.classGalleryAdpter extends BaseAdapter {

45.

46.@Override

47.publicint getCount() {

48.returnimgIds.length;

49.}

50.

51.@Override

52.publicObject getItem(int position) {

53.returnnull;

54.}

55.

56.@Override

57.publiclong getItemId(int position) {

58.return 0;

59.}

60.

61.@Override

62.publicView getView(int position, View convertView, ViewGroup parent) {

63.ImageViewimageView = new ImageView(GalleryActivity.this);

64.imageView.setImageResource(imgIds[position]);

65.imageView.setScaleType(ImageView.ScaleType.FIT_XY);

66.returnimageView;

67.}

68.}

69.}

第三步:

/GalleryDemo/AndroidManifest.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3.package="com.mygallery.activity"

4.android:versionCode="1"

5.android:versionName="1.0">

6.<application android:icon="@drawable/icon"android:label="@string/app_name">

7.<activity android:name=".GalleryActivity"

8.android:label="@string/app_name">

9.<intent-filter>

10.<action android:name="android.intent.action.MAIN"/>

11.<category android:name="android.intent.category.LAUNCHER"/>

12.</intent-filter>

13.</activity>

14.

15.</application>

16.<uses-sdk android:minSdkVersion="8"/>

17.</manifest>

效果图:

图一: 浏览效果

图二: 选中点击后的效果

源码下载地址:http://download.csdn.net/source/3203041

分享到:

· 上一篇:在Windows环境下,下载Android源代码(经过测试此方法仅能下载common,参考下载TortoiseGit办法)

· 下一篇:10. android Spinner 下拉列表

10. android Spinner 下拉列表

分类: android入门2011-04-18 21:151797人阅读评论(11)收藏举报

目录结构

第一步:

/SpinnerDemo/res/values/strings.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string name="app_name">下拉列表</string>

4.<string name="hobby">你的爱好</string>

5.<string name="basketball">篮球</string>

6.<string name="football">足球</string>

7.<string name="volleyball">排球</string>

8.</resources>

第二步:

/SpinnerDemo/res/values/colors.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<color name="black">#000000</color>

4.</resources>

第三步:

/SpinnerDemo/res/layout/spinner_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="wrap_content">

7.<TextView android:id="@+id/textView"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:textSize="28dip"

11.android:text="@string/hobby"/>

12.<Spinner android:id="@+id/spinner"

13.android:layout_width="fill_parent"

14.android:layout_height="wrap_content"

15./>

16.</LinearLayout>

第四步:

/SpinnerDemo/src/com/myspinner/demo/SpinnerActivity.java

view plaincopy to clipboardprint?

1.packagecom.myspinner.demo;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.importandroid.view.View;

6.importandroid.view.ViewGroup;

7.importandroid.widget.AdapterView;

8.importandroid.widget.BaseAdapter;

9.importandroid.widget.ImageView;

10.importandroid.widget.LinearLayout;

11.importandroid.widget.Spinner;

12.importandroid.widget.TextView;

13.importandroid.widget.AdapterView.OnItemSelectedListener;

14.

15.publicclass SpinnerActivity extends Activity {

16.

17.int[]hobbyStrIds = {R.string.basketball,

18.R.string.football,R.string.volleyball};

19.

20.int[]hobbyImgIds = {R.drawable.basketball,

21.R.drawable.football,R.drawable.volleyball};

22.

23.@Override

24.publicvoid onCreate(Bundle savedInstanceState) {

25.super.onCreate(savedInstanceState);

26.setContentView(R.layout.spinner_layout);

27.

28.Spinnerspinner = (Spinner) findViewById(R.id.spinner);

29.SpinnerAdapteradapter = new SpinnerAdapter();

30.spinner.setAdapter(adapter);

31.

32.//选中监听器

33.OnItemSelectedListenerlistener = new OnItemSelectedListener() {

34.

35.@Override

36.publicvoid onItemSelected(AdapterView<?> parent, View view,

37.intposition, long id) {

38.TextViewtextView = (TextView) findViewById(R.id.textView);

39.

40.LinearLayoutlinearLayout = (LinearLayout) view;

41.

42.TextViewspinnerTextView = (TextView) linearLayout.getChildAt(1);

43.StringBuilderstrBuilder = new StringBuilder();

44.

45.strBuilder.append(getResources().getText(R.string.hobby));

46.strBuilder.append(": ");

47.strBuilder.append(spinnerTextView.getText());

48.

49.textView.setText(strBuilder);

50.}

51.

52.@Override

53.publicvoid onNothingSelected(AdapterView<?> parent) {

54.}

55.};

56.

57.spinner.setOnItemSelectedListener(listener);

58.}

59.

60.classSpinnerAdapter extends BaseAdapter {

61.

62.@Override

63.publicint getCount() {

64.if(hobbyStrIds.length<= hobbyImgIds.length) {

65.returnhobbyStrIds.length;

66.}

67.returnhobbyImgIds.length;

68.}

69.

70.@Override

71.publicObject getItem(int position) {

72.returnnull;

73.}

74.

75.@Override

76.publiclong getItemId(int position) {

77.return 0;

78.}

79.

80.@Override

81.publicView getView(int position, View convertView, ViewGroup parent) {

82.LinearLayoutlinearLayout = new LinearLayout(SpinnerActivity.this);

83.linearLayout.setOrientation(LinearLayout.HORIZONTAL);

84.linearLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg));

85.

86.//设置小图标

87.ImageViewimageView = new ImageView(SpinnerActivity.this);

88.imageView.setImageDrawable(getResources()

89..getDrawable(hobbyImgIds[position]));

90.linearLayout.addView(imageView);

91.

92.//设置内容

93.TextViewtextView = new TextView(SpinnerActivity.this);

94.textView.setText("" + getResources().getText(hobbyStrIds[position]));

95.textView.setTextSize(24);

96.textView.setTextColor(R.color.black);

97.linearLayout.addView(textView);

98.

99.returnlinearLayout;

100.}

101.}

102.}

第五步:

/SpinnerDemo/AndroidManifest.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3.package="com.myspinner.demo"

4.android:versionCode="1"

5.android:versionName="1.0">

6.<application android:icon="@drawable/icon"android:label="@string/app_name">

7.<activity android:name=".SpinnerActivity"

8.android:label="@string/app_name">

9.<intent-filter>

10.<action android:name="android.intent.action.MAIN"/>

11.<category android:name="android.intent.category.LAUNCHER"/>

12.</intent-filter>

13.</activity>

14.

15.</application>

16.<uses-sdk android:minSdkVersion="8"/>

17.

18.</manifest>

效果图:

未展开下拉列表前

展开下拉列表后

选中下拉列表后(选中的是足球)

源码下载地址: http://download.csdn.net/source/3203345

分享到:

· 上一篇:9. android Gallery(画廊)以及BaseAdapter

· 下一篇:11. android 选项菜单(此处为icon menu)--Menu,SubMenu,MenuItem的用法

11. android 选项菜单(此处为icon menu)--Menu,SubMenu,MenuItem的用法

分类: android入门2011-04-19 22:50605人阅读评论(1)收藏举报

目录结构:

第一步:

/OptionsMenuDemo/res/values/strings.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string name="app_name">选项菜单</string>

4.<string name="label">你的选择为 /n</string>

5.<string name="gender">性别</string>

6.<string name="male"></string>

7.<string name="female"></string>

8.<string name="hobby">体育爱好</string>

9.<string name="basketball">篮球</string>

10.<string name="football">足球</string>

11.<string name="volleyball">排球</string>

12.<string name="OK">确定</string>

13.</resources>

第二步:

/OptionsMenuDemo/res/layout/options_menu_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.android:id="@+id/linearLayout"

4.xmlns:android="http://schemas.android.com/apk/res/android"

5.android:layout_width="fill_parent"

6.android:layout_height="fill_parent"

7.android:orientation="vertical">

8.

9.<ScrollView android:id="@+id/scrollView"

10.android:layout_width="fill_parent"

11.android:layout_height="fill_parent">

12.

13.<EditText android:id="@+id/editText"

14.android:layout_width="fill_parent"

15.android:layout_height="fill_parent"

16.android:editable="false"

17.android:cursorVisible="false"

18.android:text="@string/label"/>

19.</ScrollView>

20.</LinearLayout>

第三步:

/OptionsMenuDemo/src/com/myoptionsmenu/values/MenuFinalValues.java

view plaincopy to clipboardprint?

1.packagecom.myoptionsmenu.values;

2.

3.publicinterface MenuFinalValues {

4.

5.//总菜单项组的编号

6.publicstatic final int MAIN_GROUP = 0;

7.

8.//性别子菜单组的编号

9.publicstatic final int GENDER_GROUP = 1;

10.

11.//爱好子菜单组的编号

12.publicstatic final int HOBBY_GROUP = 2;

13.

14.//性别为男的选项编号

15.publicstatic final int MENU_GENDER_MALE = 3;

16.

17.//性别女的选项编号

18.publicstatic final int MENU_GENDER_FEMALE = 4;

19.

20.//爱好篮球编号

21.publicstatic final int MENU_HOBBY_BASKETBALL = 5;

22.

23.//足球

24.publicstatic final int MENU_HOBBY_FOOTBALL = 6;

25.

26.//排球

27.publicstatic final int MENU_HOBBY_VOLLEYBALL = 7;

28.

29.publicstatic final int MENU_OK = 8;

30.

31.//性别子菜单

32.publicstatic final int MENU_GENDER = 9;

33.

34.//爱好子菜单

35.publicstatic final int MENU_HOBBY = 10;

36.

37.}

第四步:

/OptionsMenuDemo/src/com/myoptionsmenu/demo/OptionsMenuActivity.java

view plaincopy to clipboardprint?

1.packagecom.myoptionsmenu.demo;

2.

3.importstatic com.myoptionsmenu.values.MenuFinalValues.*;

4.importandroid.app.Activity;

5.importandroid.os.Bundle;

6.importandroid.view.Menu;

7.importandroid.view.MenuItem;

8.importandroid.view.SubMenu;

9.importandroid.view.MenuItem.OnMenuItemClickListener;

10.importandroid.widget.EditText;

11.

12./*

13.* OptionMenu是activity的一组基本的menu items,由机器上的menu键触发。

14.* OptionMenu包含两种Menu item:Icon Menu item、Expended Menu item。

15.* IconMenu是由用户点击触发的处于界面底端的菜单。

16.* 它最大可以有六个菜单,而且是唯一支持icon功能的menu item,

17.* 也是唯一不支持checkbox和radio按钮的menu item。expanded menu是一个竖直列表。

18.* 当用户点击Icon menu的"more"选项时弹出。

19.* 它只会在Option menu超过六个时显视,Option Menu应该显视程序的基本功能或导航。

20.* 当用户第一次按menu键时,系统会调用onCreateOptionsMenu()方法,

21.* 你可能通过编程,用 add()方法增加菜单或在xml中定义。

22.* 当一个item被选中时,onOptionsitemSelected()会被回调,此时可以用 getItemId()

23.* 区分被选中的item。

24.*onCreateOptionsMenu:第一次调用时触发,用于初始化相关item

25.*/

26.publicclass OptionsMenuActivity extends Activity {

27.

28.privateMenuItem male = null;

29.

30.privateMenuItem[] hobbies = new MenuItem[3];

31.

32.@Override

33.publicvoid onCreate(Bundle savedInstanceState) {

34.super.onCreate(savedInstanceState);

35.setContentView(R.layout.options_menu_layout);

36.}

37.

38.@Override

39.publicboolean onCreateOptionsMenu(Menu menu) {

40.

41.

42.//建立性别菜单组

43.SubMenusubMenuGender = menu.addSubMenu(MAIN_GROUP, MENU_GENDER,

44.0, R.string.gender);

45.subMenuGender.setIcon(R.drawable.gender);

46.//设置子菜单图标

47.subMenuGender.setHeaderIcon(R.drawable.gender);

48.

49.//为性别子菜单项添加菜单内容

50.male =subMenuGender.add(GENDER_GROUP, MENU_GENDER_MALE,

51.0, R.string.male);

52.// 设置为默认值,即选中状态(此时后面的选中按钮未出现)

53.male.setChecked(true);

54.subMenuGender.add(GENDER_GROUP,MENU_GENDER_FEMALE, 0, R.string.female);

55.//设置GENDER_GROUP组互斥,即该组是一组单选(可以为多个)

56.subMenuGender.setGroupCheckable(GENDER_GROUP,true, true);

57.

58.

59.//建立爱好菜单组

60.SubMenusubMenuHobby = menu.addSubMenu(MAIN_GROUP, MENU_HOBBY,

61.0, R.string.hobby);

62.subMenuHobby.setIcon(R.drawable.hobby);

63.subMenuHobby.setHeaderIcon(R.drawable.hobby);

64.

65.hobbies[0] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY_BASKETBALL,

66.0, R.string.basketball);

67.//Icons只能在图标菜单中显示;它们在扩展菜单和子菜单中不可见,也就是

68.//SubMenu中的MenuItem不支持icon,所以下面 setIcon是不可见的

69.//basketball.setIcon(R.drawable.basketball);

70.//为此项添加复选按钮

71.hobbies[0].setCheckable(true);

72.hobbies[0].setChecked(true); //设置为选中状态

73.hobbies[1] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY_FOOTBALL,

74.0, R.string.football);

75.hobbies[1].setCheckable(true);

76.hobbies[2] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY_VOLLEYBALL,

77.0, R.string.volleyball);

78.hobbies[2].setCheckable(true);

79.

80.MenuItemok = menu.add(GENDER_GROUP+2, MENU_OK, 0, R.string.OK);

81.

82.OnMenuItemClickListenerlistener = new OnMenuItemClickListener() {

83.

84.@Override

85.publicboolean onMenuItemClick(MenuItem menuItem) {

86.getSubMenuStr();

87.returntrue;

88.}

89.

90.};

91.

92.ok.setOnMenuItemClickListener(listener);

93.//设置快捷键

94.ok.setAlphabeticShortcut('o');

95.returntrue;

96.}

97.

98.@Override

99.publicboolean onOptionsItemSelected(MenuItem menuItem) {

100.

101.switch(menuItem.getItemId()){

102.caseMENU_GENDER_MALE:

103.caseMENU_GENDER_FEMALE:

104.menuItem.setChecked(true);

105.getSubMenuStr();

106.break;

107.caseMENU_HOBBY_BASKETBALL:

108.caseMENU_HOBBY_FOOTBALL:

109.caseMENU_HOBBY_VOLLEYBALL:

110.menuItem.setChecked(!menuItem.isChecked());

111.getSubMenuStr();

112.break;

113.}

114.returntrue;

115.}

116.

117.privatevoid getSubMenuStr() {

118.StringBufferresult = new StringBuffer("你选择的性别为:");

119.if(male.isChecked()){

120.result.append("男");

121.} else {

122.result.append("女");

123.}

124.

125.StringBufferhobbyStr = new StringBuffer();

126.for(MenuItemitem:hobbies) {

127.if(item.isChecked()){

128.hobbyStr.append(item.getTitle()+ "、");

129.}

130.}

131.

132.if(hobbyStr.length()> 0) {

133.result.append(",你的爱好为:")

134..append(hobbyStr.substring(0, hobbyStr.length()-1))

135..append("。/n");

136.} else {

137.result.append("。/n");

138.}

139.

140.EditTexteditText = (EditText) findViewById(R.id.editText);

141.editText.append(result);

142.}

143.}

第五步:

/OptionsMenuDemo/AndroidManifest.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3.package="com.myoptionsmenu.demo"

4.android:versionCode="1"

5.android:versionName="1.0">

6.<application android:icon="@drawable/icon"android:label="@string/app_name">

7.<activity android:name=".OptionsMenuActivity"

8.android:label="@string/app_name">

9.<intent-filter>

10.<action android:name="android.intent.action.MAIN"/>

11.<category android:name="android.intent.category.LAUNCHER"/>

12.</intent-filter>

13.</activity>

14.

15.</application>

16.<uses-sdk android:minSdkVersion="8"/>

17.</manifest>

效果图:

初始化的时候(如要出现菜单,需按下Menu键)

按下MENU键后,菜单弹出

性别子菜单项

爱好子菜单项

下载地址:

http://download.csdn.net/source/3207129

分享到:

· 上一篇:10. android Spinner 下拉列表

· 下一篇:12. android ContextMenu 上下文菜单

12. android ContextMenu 上下文菜单

分类: android入门2011-04-20 21:57204人阅读评论(0)收藏举报

目录结构:

第一步:

/ContextMenuDemo/res/values/strings.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string name="app_name">上下文菜单</string>

4.<string name="male"></string>

5.<string name="female"></string>

6.<string name="basketball">篮球</string>

7.<string name="football">足球</string>

8.<string name="volleyball">排球</string>

9.<string name="gender">性别</string>

10.<string name="hobby">爱好</string>

11.<string name="genderEdit">输入性别</string>

12.<string name="hobbyEdit">输入爱好</string>

13.</resources>

第二步:

/ContextMenuDemo/res/layout/context_menu_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="fill_parent">

7.

8.<!-- 性别 -->

9.<LinearLayout

10.xmlns:android="http://schemas.android.com/apk/res/android"

11.android:orientation="horizontal"

12.android:layout_width="fill_parent"

13.android:layout_height="wrap_content">

14.

15.<TextView android:text="@string/gender"

16.android:width="100dip"

17.android:textSize="24dip"

18.android:layout_width="wrap_content"

19.android:layout_height="wrap_content"/>

20.<EditText android:id="@+id/genderEdit"

21.android:text="@string/genderEdit"

22.android:layout_width="fill_parent"

23.android:layout_height="wrap_content"

24./>

25.</LinearLayout>

26.<!-- 爱好 -->

27.<LinearLayout

28.xmlns:android="http://schemas.android.com/apk/res/android"

29.android:orientation="horizontal"

30.android:layout_width="fill_parent"

31.android:layout_height="wrap_content">

32.

33.<TextView android:text="@string/hobby"

34.android:width="100dip"

35.android:textSize="24dip"

36.android:layout_width="wrap_content"

37.android:layout_height="wrap_content"/>

38.<EditText android:id="@+id/hobbyEdit"

39.android:text="@string/hobbyEdit"

40.android:layout_width="fill_parent"

41.android:layout_height="wrap_content"/>

42.</LinearLayout>

43.</LinearLayout>

第三步:

/ContextMenuDemo/src/com/mycontextmenu/demo/MenuFinalValues.java

view plaincopy to clipboardprint?

1.packagecom.mycontextmenu.demo;

2.

3.publicinterface MenuFinalValues {

4.

5.publicstatic final int MALE = 1;

6.

7.publicstatic final int FEMALE = 2;

8.

9.publicstatic final int BASKETBALL = 3;

10.

11.publicstatic final int FOOTBALL = 4;

12.

13.publicstatic final int VOLLEYBALL = 5;

14.}

第四步:

/ContextMenuDemo/src/com/mycontextmenu/demo/ContextMenuActivity.java

view plaincopy to clipboardprint?

1.packagecom.mycontextmenu.demo;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.importandroid.view.ContextMenu;

6.importandroid.view.MenuItem;

7.importandroid.view.View;

8.importandroid.widget.EditText;

9.

10.importstatic com.mycontextmenu.demo.MenuFinalValues.*;

11.

12.publicclass ContextMenuActivity extends Activity {

13.@Override

14.publicvoid onCreate(Bundle savedInstanceState) {

15.super.onCreate(savedInstanceState);

16.setContentView(R.layout.context_menu_layout);

17.//需为EditText注册ContextMenu,否则当长按输入框时,只能弹出系统自带的

18.//ContextMenuActivity中的onCreateContextMenu未执行到

19.this.registerForContextMenu(findViewById(R.id.genderEdit));

20.this.registerForContextMenu(findViewById(R.id.hobbyEdit));

21.}

22.

23./*

24.* 只有当控件注册了才调用此方法,当长按2秒后会弹出菜单项

25.* 不支持快捷键,起菜单选项不能附带图标

26.*/

27.@Override

28.publicvoid onCreateContextMenu(ContextMenu menu, View view,

29.ContextMenu.ContextMenuInfomenuInfo) {

30.//清除系统所有系统自带的菜单项

31.//如果只想清除部分,可以使用menu.removeItem(系统自带菜单项id)

32.//注:系统自带菜单项ID,请参考http://developer.android.com/reference/android/R.id.html

33.//如,删除全部选择menu.removeItem(android.R.id.selectAll);

34.menu.clear();

35.if(view== findViewById(R.id.genderEdit)) {

36.menu.setHeaderIcon(R.drawable.gender);

37.menu.setHeaderTitle(R.string.gender);

38.//如果该菜单项里面还未添加菜单,此时菜单项是隐藏的

39.//添加了MALE后会显示出来

40.menu.add(0, MALE, 0,R.string.male);

41.menu.add(0, FEMALE, 0,R.string.female);

42.

43.} elseif(view == findViewById(R.id.hobbyEdit)) {

44.menu.setHeaderIcon(R.drawable.basketball);

45.menu.setHeaderTitle(R.string.hobby);

46.//无法为菜单项添加图标icon(即setIcon无效),android2.2不支持

47.//但是可以通过其他途径添加图标,

48.//可参考此处https://code.google.com/p/android-icon-context-menu/

49.//http://www.tanisoft.net/2010/09/android-context-menu-with-icon.html

50.menu.add(0, BASKETBALL, 0,R.string.basketball);

51.menu.add(0, FOOTBALL, 0,R.string.football);

52.menu.add(0, VOLLEYBALL, 0,R.string.volleyball);

53.}

54.}

55.

56.@Override

57.publicboolean onContextItemSelected(MenuItem menuItem) {

58.EditTexteditText = null;

59.switch(menuItem.getItemId()){

60.caseMALE:

61.caseFEMALE:

62.editText= (EditText) this.findViewById(R.id.genderEdit);

63.break;

64.caseBASKETBALL:

65.caseFOOTBALL:

66.caseVOLLEYBALL:

67.editText= (EditText) this.findViewById(R.id.hobbyEdit);

68.break;

69.}

70.editText.setText(menuItem.getTitle());

71.returntrue;

72.}

73.}

第五步:

/ContextMenuDemo/AndroidManifest.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3.package="com.mycontextmenu.demo"

4.android:versionCode="1"

5.android:versionName="1.0">

6.<application android:icon="@drawable/icon"android:label="@string/app_name">

7.<activity android:name=".ContextMenuActivity"

8.android:label="@string/app_name">

9.<intent-filter>

10.<action android:name="android.intent.action.MAIN"/>

11.<category android:name="android.intent.category.LAUNCHER"/>

12.</intent-filter>

13.</activity>

14.

15.</application>

16.<uses-sdk android:minSdkVersion="8"/>

17.

18.</manifest>

效果图:

程序运行初始状态

性别输入框长按2秒后弹出菜单

爱好输入框长按两秒,然后选中足球

菜单选中后,输入框显示所选中的内容

源码下载地址:http://download.csdn.net/source/3210223

分享到:

· 上一篇:11. android 选项菜单(此处为icon menu)--Menu,SubMenu,MenuItem的用法

· 下一篇:13. android Context Menu With Icon (英文)

13. android Context Menu With Icon (英文)

分类: android入门2011-04-21 20:25279人阅读评论(2)收藏举报

Description:
When you take a look atandroid sdk document on Context Menu, you would notice that current ContextMenu does not support for Icon. But if you do a long click on the home screenof your phone, you would see something like the image below. So how google didthat? This tutorial will guide you through the steps to archive something likethat.

Creating Demo Application:
First of all, we will create ademo application on which our context menu will be displayed. The demoapplication is just a simple one which shows a list of items (using ListView),when you do a long click on an item, the Context Menu will appear. This is asimple application with only a ListView, so we will skip through this step.

Implement Context Menu:
I've looked through the codeof Android Launcher Application, and realized that the application did notactually use Context Menu. It was implemented by using a dialog with a customlist view. So I decided to take this approach for the tutorial.
1. Create IconContextMenuItem:
This class will hold our menu item's information, including: menu title, menuicon, and menu id.

view plaincopy to clipboardprint?

1.importandroid.content.res.Resources;

2.importandroid.graphics.drawable.Drawable;

3.

4.publicclass IconContextMenuItem {

5.publicfinal CharSequence text;

6.publicfinal Drawable image;

7.publicfinal int actionTag;

8.

9.publicIconContextMenuItem(Resources res, int textResourceId,

10.intimageResourceId, int actionTag) {

11.text =res.getString(textResourceId);

12.if(imageResourceId != -1) {

13.image =res.getDrawable(imageResourceId);

14.} else {

15.image =null;

16.}

17.this.actionTag= actionTag;

18.}

19.

20.publicIconContextMenuItem(Resources res, CharSequence title,

21.intimageResourceId, int actionTag) {

22.text =title;

23.if(imageResourceId != -1) {

24.image =res.getDrawable(imageResourceId);

25.} else {

26.image =null;

27.}

28.this.actionTag= actionTag;

29.}

30.}

2. Create IconMenuAdapter:
This will be the menu itemlist adapter, holding all items of context menu. So in this class, there willbe an array list of type IconContextMenuItem as below:

view plaincopy to clipboardprint?

1.protectedclass IconMenuAdapter extends BaseAdapter {

2.

3.privateArrayList<IconContextMenuItem> mItems =

4.newArrayList<IconContextMenuItem>();

5.}

In this class, we need tooverride the method getView, in which we will create custom view for ourmenu item (that will be an Icon followed by a TextView)

view plaincopy to clipboardprint?

1.@Override

2.publicView getView(int position, View convertView, ViewGroup parent) {

3.IconContextMenuItemitem = (IconContextMenuItem) getItem(position);

4.Resourcesres = parentActivity.getResources();

5.if(convertView == null) {

6.TextViewtemp = new TextView(context);

7.AbsListView.LayoutParamsparam = new AbsListView.LayoutParams(

8.AbsListView.LayoutParams.FILL_PARENT,

9.AbsListView.LayoutParams.WRAP_CONTENT);

10.temp.setLayoutParams(param);

11.temp.setPadding((int)toPixel(res, 15),

12.0, (int) toPixel(res, 15),0);

13.temp.setGravity(android.view.Gravity.CENTER_VERTICAL);

14.Theme th= context.getTheme();

15.TypedValuetv = new TypedValue();

16.if(th.resolveAttribut(android.R.attr.textAppearanceLargeInverse,

17.tv,true)) {

18.temp.setTextAppearance(context,tv.resourceId);

19.}

20.temp.setMinHeight(LIST_PREFERED_HEIGHT);

21.temp.setCompoundDrawablePadding((int)toPixel(res, 14));

22.convertView= temp;

23.}

24.TextViewtextView = (TextView) convertView;

25.textView.setTag(item);

26.textView.setText(item.text);

27.textView.setCompoundDrawablesWithIntrinsicBounds(item.image,

28.null,null,null);

29.returntextView;

30.}


3. Create IconContextMenu:
This class is the main classof the context menu, which creates a context-menu-liked dialog for theapplication. In this class, we will write createMenu() method that return aDialog object.

view plaincopy to clipboardprint?

1.publicclass IconContextMenu implements DialogInterface.OnCancelListener,

2.DialogInterface.OnDismissListener{

3./**

4.* Createmenu

5.*/

6.publicDialog createMenu(String menuItitle) {

7.finalAlertDialog.Builder builder =

8.newAlertDialog.Builder(parentActivity);

9.builder.setTitle(menuItitle);

10.builder.setAdapter(menuAdapter,new DialogInterface.OnClickListener() {

11.

12.@Override

13.publicvoid onClick(DialogInterface dialoginterface,

14.int i) {

15.IconContextMenuItemitem =

16.(IconContextMenuItem)menuAdapter.getItem(i);

17.if(clickHandler != null) {

18.clickHandler.onClick(item.actionTag);

19.}

20.}

21.});

22.builder.setInverseBackgroundForced(true);

23.AlertDialogdialog = builder.create();

24.dialog.setOnCancelListener(this);

25.dialog.setOnDismissListener(this);

26.returndialog;

27.}

28.

29./**

30.* Addmenu item

31.* @parammenuItem

32.*/

33.publicvoid addItem(Resources res, CharSequence title,

34.intimageResourceId, int actionTag) {

35.menuAdapter.addItem(newIconContextMenuItem(res,

36.title,imageResourceId, actionTag));

37.}

38.

39./**

40.* Setmenu onclick listener

41.* @paramlistener

42.*/

43.publicvoid setOnClickListener(IconContextMenuOnClickListener listener) {

44.clickHandler= listener;

45.}

46.

47.}

You would also notice that inthis class there two other methods: addItem (which adds new Menu Item toContext Menu) and setOnClickListener (which adds menu's click handler method).
So we have finished our implement of Context Menu with Icon supported. Nextstep will show you how to use the above implemented class in our activity.

Use Context Menu with Icon in Activity:
Firstly, we need to initialize our context menu (declare context menu, additems,...)

view plaincopy to clipboardprint?

1.publicclass MainActivity extends Activity {

2.privateIconContextMenu iconContextMenu = null;

3.@Override public void onCreate(BundlesavedInstanceState) {

4.//....

5.//initthe menu

6.iconContextMenu= new IconContextMenu(this, CONTEXT_MENU_ID);

7.iconContextMenu.addItem(res,"Menu Item 1",

8.R.drawable.ic_1,MENU_ITEM_1_ACTION);

9.iconContextMenu.addItem(res,"Menu Item 2",

10.R.drawable.ic_2,MENU_ITEM_2_ACTION);

11.iconContextMenu.addItem(res,"Menu Item 3",

12.R.drawable.ic_3,MENU_ITEM_3_ACTION);

13.iconContextMenu.addItem(res,"Menu Item 4",

14.R.drawable.ic_4,MENU_ITEM_4_ACTION);

15.

16.//setonclick listener for context menu

17.iconContextMenu.setOnClickListener(newIconContextMenu.IconContextMenuOnClickListener() {

18.@Override

19.publicvoid onClick(int menuId) {

20.switch(menuId){

21.caseMENU_ITEM_1_ACTION:

22.Toast.makeText(getApplicationContext(),

23."You'veclicked on menu item 1", 1000).show();

24.break;

25.caseMENU_ITEM_2_ACTION:

26.Toast.makeText(getApplicationContext(),

27."You'veclicked on menu item 2", 1000).show();

28.break;

29.caseMENU_ITEM_3_ACTION:

30.Toast.makeText(getApplicationContext(),

31."You'veclicked on menu item 3", 1000).show();

32.break;

33.caseMENU_ITEM_4_ACTION:

34.Toast.makeText(getApplicationContext(),

35."You'veclicked on menu item 4", 1000).show();

36.break;

37.}

38.}

39.});

40.}

41.

42.}

Our Context Menu is actually aDialog, so in order to use it in activity, we have to override theonCreateDialog method of the Activity.

view plaincopy to clipboardprint?

1./** *create context menu */

2.@Override

3.protectedDialog onCreateDialog(int id) {

4.if (id ==CONTEXT_MENU_ID) {

5.returniconContextMenu.createMenu("Menu Title");

6.}

7.returnsuper.onCreateDialog(id);

8.}

Here, we have finishedimplementing our Context Menu with Icon on Android. The result of thisimplementation is as the image below:


Notice:
The above is just the majorsteps to show you how to implement a Context Menu with Icon, not a completerunable source. So, you should refer to the source code for the fullimplementation of this tutorial.

Source:

You can get source from: http://download.csdn.net/source/3213566

分享到:

· 上一篇:12. android ContextMenu 上下文菜单

· 下一篇:14. android dialog——普通对话框原

公告:CSDN新版博客排名规则公示,请各位用户周知

14. android dialog——普通对话框原理

分类: android入门2011-04-23 01:58948人阅读评论(2)收藏举报

先看过效果图:

图1 输入框默认文字为"这是一个普通对话框。" 图2 当点击"显示普通对话框"后,将弹出一个对话框


图3 点击图2中的对话框的确定按钮, 输入框里输入自己的内容 图4 点击图3中的“显示普通对话框”后弹出对话框

第一步:建立res/values/string.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?><resources> <string name="app_name">普通对话框</string> <string name="button">显示普通对话框</string> <string name="title">普通对话框</string> <string name="ok">确定</string> <string name="message">这是一个普通对话框。</string></resources>

第二步:建立res/layout/common_dialog_layout.xml用来创建输入框和“显示普通对话框”按钮

view plaincopy to clipboardprint?

1.<?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="wrap_content"> <EditTextandroid:id="@+id/editText"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/message"/> <Buttonandroid:id="@+id/button"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/button"/></LinearLayout>

第三步: 分析:

关于src/com/mycommondialog/activity/CommonDialogActivity.java

1.首先对“显示普通对话框”按钮进行事件监听,即当点击这个按钮后显示对话框

view plaincopy to clipboardprint?

1.View.OnClickListenerlistener = new View.OnClickListener() {@Overridepublicvoid onClick(View view){showDialog(COMMON_DIALOG);}};button.setOnClickListener(listener);//对button事件监听

这里showDialog(int)用来显示对话框的,是系统自带的方法,当点击button产生时间后,调用该方法,首先该方法会判断Activity是否保存了对话框对象

(1)如果未保存则调用onCreateDialog(int),然后再调用onPrepareDialog(int, Dialog)

(2)如果保存了对话框对象,则直接调用onPrepareDialog(int, Dialog),不会再去create,所以有时候当你再输入框里无论如何输入什么内容,对话框的内容都是第一次产生的。

2. Activity 未保存对话框对象,则会创建对话框,即调用onCreateDialog(int)

view plaincopy to clipboardprint?

1.protectedDialog onCreateDialog(int id) {EditText editText = (EditText)findViewById(R.id.editText);switch(id) { case COMMON_DIALOG: Builder builder =new AlertDialog.Builder(this); builder.setIcon(R.drawable.dialog);builder.setTitle(R.string.button); builder.setMessage(editText.getText());DialogInterface.OnClickListener listener = newDialogInterface.OnClickListener() {@Overridepublicvoid onClick(DialogInterface dialog, int which){removeDialog(COMMON_DIALOG);}};builder.setPositiveButton(R.string.ok,listener);dialog = builder.create(); break;}return dialog;}

需要newAlertDialog.Builder(this)用来存放Dialog的内容(如图标,标题和信息),this是针对此Activity的。

setPositiveButton表示中间的那个button按钮(一般情况下button有三个按钮,此处只显示中间的那个按钮)

removeDialog(int)是用来清除Activity保存下来的Dialog对象,如果不加removeDialog将会导致无论在对话框里输入什么内容,

弹出来的对话框始终都是第一次保留下来的,这里所以要加上它

3. 关于onPrepareDialog(int, Dialog), 每次点击“显示普通对话框”按钮都会去调用此方法。

view plaincopy to clipboardprint?

1.@Override protected voidonPrepareDialog(int id, Dialog dialog) { dialog.show(); }

dialog.show()其实意义不大,加与不加系统都会调用show的,而且只显示一个对话框,dialog中isShowing()来判断是否该对话框正在显示了,为了验证可以将onPrepareDialog(int, Dialog)改成下面情况(只针对下列改动)

view plaincopy to clipboardprint?

1.protectedvoid onPrepareDialog(int id, Dialog dialog){dialog.show();dialog.show();dialog.show();dialog.show();dialog.show();dialog.show();}

或者

view plaincopy to clipboardprint?

1.protectedvoid onPrepareDialog(int id, Dialog dialog) {}

结果dialog显示一个,而不会有多个对话框出现。

关于整个CommonDialogActivity代码如下(src/com/mycommondialog/activity/CommonDialogActivity.java)

view plaincopy to clipboardprint?

1.packagecom.mycommondialog.activity;import android.app.Activity;importandroid.app.AlertDialog;import android.app.Dialog;import android.app.AlertDialog.Builder;importandroid.content.DialogInterface;import android.os.Bundle;importandroid.util.Log;import android.view.View;import android.widget.Button;importandroid.widget.EditText;/** * * @author jamesliu * */public class CommonDialogActivityextends Activity {final int COMMON_DIALOG = 1;privateDialog dialog = null;@Overridepublic voidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.common_dialog_layout);Buttonbutton = (Button) findViewById(R.id.button);View.OnClickListener listener = newView.OnClickListener() {@Overridepublic voidonClick(View view){showDialog(COMMON_DIALOG);}};button.setOnClickListener(listener);}/* * 使用onCreateDialog(int)来管理对话框的状态, * 那么每次对话框被解除时, * 该对话框对象的状态会被Activity保存. 调用 * removeDialog(int)将所有该对象的内部引用 * 移除 如本程序那样,如果不加removeDialog, * 那么显示的是第一次的内容 */@Overrideprotected Dialog onCreateDialog(int id){EditText editText = (EditText) findViewById(R.id.editText);switch (id) {caseCOMMON_DIALOG:Builder builder = new AlertDialog.Builder(this);builder.setIcon(R.drawable.dialog);builder.setTitle(R.string.button);builder.setMessage(editText.getText());DialogInterface.OnClickListenerlistener = new DialogInterface.OnClickListener() {@Overridepublicvoid onClick(DialogInterface dialog, int which) {// 将此处移除后,无论怎么修改EditText内容// 每次点击显示普通对话框,总是第一次的内容// 如果想更新EditText内容就得加removeDialogremoveDialog(COMMON_DIALOG);}};builder.setPositiveButton(R.string.ok,listener);dialog =builder.create();break;default:break;}Log.e("onCreateDialog","onCreateDialog");return dialog;}@Overrideprotected voidonPrepareDialog(int id, Dialog dialog) {Log.e("onPrepareDialog","onPrepareDialog");}}

最后贴出目录结构

源码下载地址:http://download.csdn.net/down/3217796/jamesliulyc

分享到:

· 上一篇:13. android Context Menu With Icon (英文)

· 下一篇:15. android dialog ——列表对话框

15. android dialog ——列表对话框

分类: android入门2011-04-23 15:04690人阅读评论(3)收藏举报

效果图:

初始状态

点击“显示列表对话框”按钮

点击对话框中的“足球”后,输入框显示的结果

第一步:

首先将列表对话框列表项中的字符数据(篮球、足球和排球)放在res/values/array.xml中

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string-array name="hobby">

4.<item>篮球</item>

5.<item>足球</item>

6.<item>排球</item>

7.</string-array>

8.</resources>

第二步:

在res/layout/list_dialog_layout.xml里定义一个输入框和一个按钮

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="wrap_content">

7.<EditText android:id="@+id/editText"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:text="这是一个列表对话框Demo"/>

11.<Button android:id="@+id/button"

12.android:layout_width="fill_parent"

13.android:layout_height="wrap_content"

14.android:text="显示列表对话框 "

15./>

16.</LinearLayout>

第三步:

产生对话框,需要AlertDialog.Builder作为载体,也就是说AlertDialog.Builder来充当内容部分的载体

对于列表对话框来说使用setItems,将array.xml中的数据关联到buidler里面

view plaincopy to clipboardprint?

1.builder.setItems(R.array.hobby,listener);

定义一个监听器监听列表项中的单击事件

view plaincopy to clipboardprint?

1.DialogInterface.OnClickListenerlistener =

2.newDialogInterface.OnClickListener() {

3.

4.@Override

5.publicvoid onClick(DialogInterface dialogInterface, int which) {

6.EditTexteditText = (EditText) findViewById(R.id.editText);

7.editText.setText("你选择了: " +

8.getResources().getStringArray(R.array.hobby)[which]);

9.}

10.};

关于整个ListDialogActivity代码如下:

view plaincopy to clipboardprint?

1.packagecom.mylistdialog.activity;

2.

3.importandroid.app.Activity;

4.importandroid.app.AlertDialog;

5.importandroid.app.Dialog;

6.importandroid.app.AlertDialog.Builder;

7.importandroid.content.DialogInterface;

8.importandroid.os.Bundle;

9.importandroid.view.View;

10.importandroid.widget.Button;

11.importandroid.widget.EditText;

12.

13./**

14.* @authorjamesliu

15.*/

16.publicclass ListDialogActivity extends Activity {

17.

18.privatefinal int LISTDIALOG = 1;

19.@Override

20.publicvoid onCreate(Bundle savedInstanceState) {

21.super.onCreate(savedInstanceState);

22.setContentView(R.layout.list_dialog_layout);

23.Buttonbutton = (Button) findViewById(R.id.button);

24.View.OnClickListenerlistener = new View.OnClickListener() {

25.@Override

26.publicvoid onClick(View view) {

27.showDialog(LISTDIALOG);

28.}

29.};

30.

31.button.setOnClickListener(listener);

32.}

33.

34.@Override

35.protectedDialog onCreateDialog(int id) {

36.Dialogdialog = null;

37.switch(id){

38.caseLISTDIALOG:

39.Builderbuilder = new AlertDialog.Builder(this);

40.builder.setTitle("列表对话框");

41.builder.setIcon(R.drawable.dialog);

42.DialogInterface.OnClickListenerlistener =

43.newDialogInterface.OnClickListener() {

44.

45.@Override

46.publicvoid onClick(DialogInterface dialogInterface,

47.intwhich) {

48.EditTexteditText =

49.(EditText)findViewById(R.id.editText);

50.editText.setText("你选择了: " +getResources()

51..getStringArray(R.array.hobby)[which]);

52.}

53.};

54.builder.setItems(R.array.hobby,listener);

55.dialog =builder.create();

56.break;

57.}

58.returndialog;

59.}

60.}

目录结构:

源码下载地址:http://download.csdn.net/source/3219029

接下将列表对话框扩展为参见(16. android dialog ——列表项带图标的列表对话框)

分享到:

· 上一篇:14. android dialog——普通对话框原理

· 下一篇:16. android dialog ——列表项带图标的列表对话框、模拟菜单项带图标

16. android dialog ——列表项带图标的列表对话框、模拟菜单项带图标

分类: android入门2011-04-23 21:52968人阅读评论(2)收藏举报

1、将TextView装载到列表项中去就可以实现带图标的列表项,这里需要借助BaseAdapter适配器来实现,然后通过getView将TextView返回就OK。

设置图片资源到TextView需要用到setCompoundDrawable(left,top,right,bottom)此方法,如下:

view plaincopy to clipboardprint?

1.textView.setCompoundDrawablesWithIntrinsicBounds(imgIds[position],0, 0, 0);

imgIds是图片资源数组,即将图片资源设置到TextView的左边(文字在右边,相对位置为文字)

具体设置TextView如下:

view plaincopy to clipboardprint?

1.TextViewtextView =

2.newTextView(IconListDialogActivity.this);

3.//获得array.xml中的数组资源getStringArray返回的是一个String数组

4.Stringtext = getResources().getStringArray(R.array.hobby)[position];

5.textView.setText(text);

6.//设置字体大小

7.textView.setTextSize(24);

8.AbsListView.LayoutParamslayoutParams = new AbsListView.LayoutParams(

9.LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);

10.textView.setLayoutParams(layoutParams);

11.//设置水平方向上居中

12.textView.setGravity(android.view.Gravity.CENTER_VERTICAL);

13.textView.setMinHeight(65);

14.//设置文字颜色

15.textView.setTextColor(Color.BLACK);

16.//设置图标在文字的左边

17.textView.setCompoundDrawablesWithIntrinsicBounds(imgIds[position],0, 0, 0);

18.//设置textView的左上右下的padding大小

19.textView.setPadding(15, 0, 15, 0);

20.//设置文字和图标之间的padding大小

21.textView.setCompoundDrawablePadding(15);

关于BaseAdapter具体用法和对话框原理,参考spinner下拉列表和普通对话框原理

2、模拟菜单项带图标

对于菜单的子菜单项,无论是上下文菜单ContextMenu还是SubMenu都不支持图片资源,这里针对输入框的上下文菜单的简单模拟(其他类似)。输入框长按将弹出菜单,故需要对输入框长按事件监听,如下

view plaincopy to clipboardprint?

1.EditTexteditText = (EditText) findViewById(R.id.editText);

2.View.OnLongClickListenereditListener =

3.newView.OnLongClickListener() {

4.@Override

5.publicboolean onLongClick(View view) {

6.showDialog(ICON_LIST_DIALOG);

7.returntrue;

8.}

9.};

10.editText.setOnLongClickListener(editListener);

---------------------------------------------------------------------------------------------------------

实现步骤

第一步:定义res/values/array.xml用来存放列表项文字内容

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string-array name="hobby">

4.<item>篮球</item>

5.<item>足球</item>

6.<item>排球</item>

7.</string-array>

8.</resources>

第二步:接下来还是一个输入框和一个按钮,如下

res/layout/icon_list_dialog_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="wrap_content">

7.<EditText android:id="@+id/editText"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:text="长按输入框将弹出上下文菜单ContextMenu"/>

11.<Button android:id="@+id/button"

12.android:layout_width="fill_parent"

13.android:layout_height="wrap_content"

14.android:text="显示列表对话框 "

15./>

16.</LinearLayout>

第三步:src/com/myiconlistdialog/activity/IconListDialogActivity.java

view plaincopy to clipboardprint?

1.packagecom.myiconlistdialog.activity;

2.

3.importandroid.app.Activity;

4.importandroid.app.AlertDialog;

5.importandroid.app.Dialog;

6.importandroid.app.AlertDialog.Builder;

7.importandroid.content.DialogInterface;

8.importandroid.graphics.Color;

9.importandroid.os.Bundle;

10.importandroid.view.View;

11.importandroid.view.ViewGroup;

12.importandroid.view.ViewGroup.LayoutParams;

13.importandroid.widget.AbsListView;

14.importandroid.widget.BaseAdapter;

15.importandroid.widget.Button;

16.importandroid.widget.EditText;

17.importandroid.widget.TextView;

18.

19.publicclass IconListDialogActivity extends Activity {

20.

21.privateint[] imgIds = {R.drawable.basketball,

22.R.drawable.football,R.drawable.volleyball};

23.

24.privatefinal int ICON_LIST_DIALOG = 1;

25.@Override

26.publicvoid onCreate(Bundle savedInstanceState) {

27.super.onCreate(savedInstanceState);

28.setContentView(R.layout.icon_list_dialog_layout);

29.

30.Buttonbutton = (Button) findViewById(R.id.button);

31.View.OnClickListenerbtnListener = new View.OnClickListener() {

32.

33.@Override

34.publicvoid onClick(View view) {

35.showDialog(ICON_LIST_DIALOG);

36.}

37.};

38.button.setOnClickListener(btnListener);

39.

40.EditTexteditText = (EditText) findViewById(R.id.editText);

41.View.OnLongClickListenereditListener =

42.newView.OnLongClickListener() {

43.@Override

44.publicboolean onLongClick(View view) {

45.showDialog(ICON_LIST_DIALOG);

46.returntrue;

47.}

48.};

49.editText.setOnLongClickListener(editListener);

50.

51.}

52.

53.

54.@Override

55.protectedDialog onCreateDialog(int id) {

56.Dialogdialog = null;

57.switch(id){

58.caseICON_LIST_DIALOG:

59.Builderbuilder = new AlertDialog.Builder(this);

60.builder.setIcon(R.drawable.basketball);

61.builder.setTitle("体育爱好");

62.BaseAdapteradapter = new ListItemAdapter();

63.DialogInterface.OnClickListenerlistener =

64.newDialogInterface.OnClickListener() {

65.@Override

66.publicvoid onClick(DialogInterface dialogInterface, int which) {

67.EditTexteditText =

68.(EditText)findViewById(R.id.editText);

69.editText.setText("你选择了: " +getResources()

70..getStringArray(R.array.hobby)[which]);

71.}

72.};

73.builder.setAdapter(adapter,listener);

74.dialog =builder.create();

75.break;

76.}

77.returndialog;

78.}

79.

80.

81.classListItemAdapter extends BaseAdapter {

82.

83.@Override

84.publicint getCount() {

85.returnimgIds.length;

86.}

87.

88.@Override

89.publicObject getItem(int position) {

90.returnnull;

91.}

92.

93.@Override

94.publiclong getItemId(int position) {

95.return 0;

96.}

97.

98.@Override

99.publicView getView(int position,

100.ViewcontentView, ViewGroup parent) {

101.TextViewtextView =

102.newTextView(IconListDialogActivity.this);

103.//获得array.xml中的数组资源getStringArray返回的是一个String数组

104.Stringtext = getResources().getStringArray(R.array.hobby)[position];

105.textView.setText(text);

106.//设置字体大小

107.textView.setTextSize(24);

108.AbsListView.LayoutParamslayoutParams = new AbsListView.LayoutParams(

109.LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);

110.textView.setLayoutParams(layoutParams);

111.//设置水平方向上居中

112.textView.setGravity(android.view.Gravity.CENTER_VERTICAL);

113.textView.setMinHeight(65);

114.//设置文字颜色

115.textView.setTextColor(Color.BLACK);

116.//设置图标在文字的左边

117.textView.setCompoundDrawablesWithIntrinsicBounds(imgIds[position],0, 0, 0);

118.//设置textView的左上右下的padding大小

119.textView.setPadding(15, 0, 15, 0);

120.//设置文字和图标之间的padding大小

121.textView.setCompoundDrawablePadding(15);

122.returntextView;

123.}

124.

125.

126.}

127.}

目录结构

效果图:

初始状态 单击按钮或者长按输入框

源代码地址:http://download.csdn.net/source/3220141

分享到:

· 上一篇:15. android dialog ——列表对话框

· 下一篇:17. android dialog —— 单选列表对话框

17. android dialog —— 单选列表对话框

分类: android入门2011-04-24 14:37851人阅读评论(0)收藏举报

设置单选列表只需 AlertDialog.Builder里面的setSingleChoiceItems 来设置即可

实现步骤如下:

第一步:用来显示列表内容的

res/values/array.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string-array name="hobby">

4.<item>篮球</item>

5.<item>足球</item>

6.<item>排球</item>

7.</string-array>

8.</resources>

第二步:还是定义一个输入框和一个按钮

res/layout/single_choice_dialog_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="wrap_content">

7.<EditText android:id="@+id/editText"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:text="这是一个单选列表对话框"

11./>

12.<Button android:id="@+id/button"

13.android:layout_width="fill_parent"

14.android:layout_height="wrap_content"

15.android:text="显示单选列表对话框"

16./>

17.</LinearLayout>

第三步:

产生一个单选列表对话框,首先需要new 一个AlertDialog.Builder作为对话框内容的载体,然后通过setSingleChoiceItems将

builder与array.xml中的数据关联,需要通过DialogInterface.OnClickListener对列表单选单击事件进行处理,

为了保存单选列表项中的选中数据,需要单独写一个类,且类中需要加一个选中了哪一个列表项的属性which,

代码如下

src/com/dialog/activity/SingChoiceDialogActivity.java

view plaincopy to clipboardprint?

1.packagecom.dialog.activity;

2.

3.importandroid.app.Activity;

4.importandroid.app.AlertDialog;

5.importandroid.app.Dialog;

6.importandroid.app.AlertDialog.Builder;

7.importandroid.content.DialogInterface;

8.importandroid.os.Bundle;

9.importandroid.util.Log;

10.importandroid.view.View;

11.importandroid.widget.Button;

12.importandroid.widget.EditText;

13.

14.publicclass SingChoiceDialogActivity extends Activity {

15.

16.privatefinal int SING_CHOICE_DIALOG = 1;

17.@Override

18.publicvoid onCreate(Bundle savedInstanceState) {

19.super.onCreate(savedInstanceState);

20.setContentView(R.layout.single_choice_dialog_layout);

21.

22.Buttonbutton = (Button) findViewById(R.id.button);

23.View.OnClickListenerlistener = new View.OnClickListener() {

24.

25.@Override

26.publicvoid onClick(View view) {

27.showDialog(SING_CHOICE_DIALOG);

28.}

29.};

30.button.setOnClickListener(listener);

31.}

32.

33.@Override

34.protectedDialog onCreateDialog(int id) {

35.Dialogdialog = null;

36.switch(id){

37.caseSING_CHOICE_DIALOG:

38.Builderbuilder = new AlertDialog.Builder(this);

39.builder.setIcon(R.drawable.basketball);

40.builder.setTitle("体育爱好");

41.finalChoiceOnClickListener choiceListener =

42.newChoiceOnClickListener();

43.builder.setSingleChoiceItems(R.array.hobby,0, choiceListener);

44.

45.DialogInterface.OnClickListenerbtnListener =

46.newDialogInterface.OnClickListener() {

47.@Override

48.publicvoid onClick(DialogInterface dialogInterface, int which) {

49.

50.EditTexteditText = (EditText) findViewById(R.id.editText);

51.intchoiceWhich = choiceListener.getWhich();

52.StringhobbyStr =

53.getResources().getStringArray(R.array.hobby)[choiceWhich];

54.editText.setText("你选择了 " + hobbyStr);

55.}

56.};

57.builder.setPositiveButton("确定", btnListener);

58.dialog =builder.create();

59.break;

60.}

61.returndialog;

62.}

63.

64.privateclass ChoiceOnClickListener implements DialogInterface.OnClickListener {

65.

66.privateint which = 0;

67.@Override

68.publicvoid onClick(DialogInterface dialogInterface, int which) {

69.this.which= which;

70.}

71.

72.publicint getWhich() {

73.returnwhich;

74.}

75.}

76.}

效果图:

源码下载地址:http://download.csdn.net/source/3221459

分享到:

· 上一篇:16. android dialog ——列表项带图标的列表对话框、模拟菜单项带图标

· 下一篇:18. android dialog —— 多选列表对话框

18. android dialog —— 多选列表对话框

分类: android入门2011-04-24 23:21851人阅读评论(1)收藏举报

和单选列表对话框相似,这里需要通过setMultiChoiceItems将array.xml中的数据添加进去。

当单击列表项时会产生Click事件,这里用到的监听器是DialogInterface.OnMultiChoiceClickListener,具体实现如下:

第一步:

添加res/values/array.xml的数据

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string-array name="hobby">

4.<item>篮球</item>

5.<item>足球</item>

6.<item>排球</item>

7.</string-array>

8.</resources>

第二步:一个输入框和一个按钮

res/layout/muti_choice_dialog_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="wrap_content">

7.<EditText android:id="@+id/editText"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:text="这是一个多选列表对话框"

11./>

12.<Button android:id="@+id/button"

13.android:layout_width="fill_parent"

14.android:layout_height="wrap_content"

15.android:text="显示多选列表对话框"

16./>

17.</LinearLayout>

第三步:

src/com/dialog/activity/MutiChoiceDialogActivity.java

view plaincopy to clipboardprint?

1.packagecom.dialog.activity;

2.

3.importandroid.app.Activity;

4.importandroid.app.AlertDialog;

5.importandroid.app.AlertDialog.Builder;

6.importandroid.app.Dialog;

7.importandroid.content.DialogInterface;

8.importandroid.os.Bundle;

9.importandroid.view.View;

10.importandroid.widget.Button;

11.importandroid.widget.EditText;

12.

13.publicclass MutiChoiceDialogActivity extends Activity {

14.

15.privatefinal int MUTI_CHOICE_DIALOG = 1;

16.

17.boolean[]selected = new boolean[]{false,false,false};

18.

19.@Override

20.publicvoid onCreate(Bundle savedInstanceState) {

21.super.onCreate(savedInstanceState);

22.setContentView(R.layout.muti_choice_dialog_layout);

23.

24.Buttonbutton = (Button) findViewById(R.id.button);

25.View.OnClickListenerlistener = new View.OnClickListener() {

26.

27.@Override

28.publicvoid onClick(View view) {

29.showDialog(MUTI_CHOICE_DIALOG);

30.}

31.};

32.button.setOnClickListener(listener);

33.}

34.

35.@Override

36.protectedDialog onCreateDialog(int id) {

37.Dialogdialog = null;

38.switch(id){

39.caseMUTI_CHOICE_DIALOG:

40.Builderbuilder = new AlertDialog.Builder(this);

41.builder.setTitle("多选列表对话框");

42.builder.setIcon(R.drawable.basketball);

43.DialogInterface.OnMultiChoiceClickListenermutiListener =

44.newDialogInterface.OnMultiChoiceClickListener() {

45.

46.@Override

47.publicvoid onClick(DialogInterface dialogInterface,

48.intwhich, boolean isChecked) {

49.selected[which]= isChecked;

50.}

51.};

52.builder.setMultiChoiceItems(R.array.hobby,selected, mutiListener);

53.DialogInterface.OnClickListenerbtnListener =

54.newDialogInterface.OnClickListener() {

55.@Override

56.publicvoid onClick(DialogInterface dialogInterface, int which) {

57.StringselectedStr = "";

58.for(inti=0; i<selected.length; i++) {

59.if(selected[i]== true) {

60.selectedStr= selectedStr + " " +

61.getResources().getStringArray(R.array.hobby)[i];

62.}

63.}

64.

65.EditTexteditText = (EditText) findViewById(R.id.editText);

66.editText.setText(selectedStr);

67.}

68.};

69.builder.setPositiveButton("确定", btnListener);

70.dialog =builder.create();

71.break;

72.}

73.returndialog;

74.}

75.}

效果图:

源码下载地址:http://download.csdn.net/source/3222814

分享到:

· 上一篇:17. android dialog —— 单选列表对话框

· 下一篇:19. android dialog —— 日期和时间选择对话框

19. android dialog —— 日期和时间选择对话框

分类: android入门2011-04-25 21:21685人阅读评论(0)收藏举报

日期和时间选择对话框,首先是要获得当前时间,这里用 java类中的Calendar来获得日期和时间(也可以用Date,但是不提倡,Date部分方法已经注释为过时), Calendar是一个抽象类,是通过getInstance()来获得实例

日期和时间选择对话框无需在像前面一样借组与AlertDialog.Builder来作为内容的载体,有直接的Dialog,其实源码里面已经包括了Builder。

1、DatePickerDialog 是日期Dialog,如下建立

view plaincopy to clipboardprint?

1.dialog =new DatePickerDialog(this,

2.dateListener,

3.calendar.get(Calendar.YEAR),

4.calendar.get(Calendar.MONTH),

5.calendar.get(Calendar.DAY_OF_MONTH));

this 表示当前 Acitivity,表示这是当前Acitivity的对话框

dateListener为产生日期事件的监听器,这里是通过DatePickerDialog.OnDateSetListener来获得,代码如下

view plaincopy to clipboardprint?

1.DatePickerDialog.OnDateSetListenerdateListener =

2.newDatePickerDialog.OnDateSetListener() {

3.@Override

4.publicvoid onDateSet(DatePicker datePicker,

5.int year,int month, int dayOfMonth) {

6.EditTexteditText =

7.(EditText)findViewById(R.id.editText);

8.//Calendar月份是从0开始,所以month要加1

9.editText.setText("你选择了" + year + "年" +

10.(month+1) + "月" + dayOfMonth + "日");

11.}

12.};

这里注意的是calendar.getCalendar(Calendar.MONTH), Calendar类中是从0开始取月份的,但是这里DatePickerDialog已经做了处理。

2、TimePickerDialog为时间选择对话框,实现代码如下:

view plaincopy to clipboardprint?

1.dialog =new TimePickerDialog(this, timeListener,

2.calendar.get(Calendar.HOUR_OF_DAY),

3.calendar.get(Calendar.MINUTE),

4.false);//是否为二十四制

timeListener 是一个TimePickerDialog.OnTimeSetListener实例。

效果图如下:

这是日期选择对话框 这是时间选择对话框

实现步骤:

第一步:一个用来显示选择的内容的输入框和两个用来显示日期和时间的按钮

res/layout/date_time_dialog_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

3.android:orientation="vertical"

4.android:layout_width="fill_parent"

5.android:layout_height="fill_parent"

6.>

7.<EditText android:id="@+id/editText"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:editable="false"

11.android:cursorVisible="false"/>

12.<Button android:id="@+id/btnDate"

13.android:text="显示日期选择对话框"

14.android:layout_width="fill_parent"

15.android:layout_height="wrap_content"/>

16.<Button android:id="@+id/btnTime"

17.android:text="显示时间选择对话框"

18.android:layout_width="fill_parent"

19.android:layout_height="wrap_content" />

20.</LinearLayout>

第二步:

在DateTimeDialogActivity的OnCreate方法里面要对两个button进行单击事件处理,OnCreateDialog来处理产生对话框

src/com/dialog/activity/DateTimeDialogActivity.java

view plaincopy to clipboardprint?

1.packagecom.dialog.activity;

2.

3.importjava.util.Calendar;

4.

5.importandroid.app.Activity;

6.importandroid.app.DatePickerDialog;

7.importandroid.app.Dialog;

8.importandroid.app.TimePickerDialog;

9.importandroid.os.Bundle;

10.importandroid.view.View;

11.importandroid.widget.Button;

12.importandroid.widget.DatePicker;

13.importandroid.widget.EditText;

14.importandroid.widget.TimePicker;

15.

16.publicclass DateTimeDialogActivity extends Activity {

17.

18.privatefinal int DATE_DIALOG = 1;

19.

20.privatefinal int TIME_DIALOG = 2;

21.@Override

22.publicvoid onCreate(Bundle savedInstanceState) {

23.super.onCreate(savedInstanceState);

24.setContentView(R.layout.date_time_dialog_layout);

25.

26.View.OnClickListenerdateBtnListener =

27.newBtnOnClickListener(DATE_DIALOG);

28.

29.ButtonbtnDate = (Button) findViewById(R.id.btnDate);

30.btnDate.setOnClickListener(dateBtnListener);

31.

32.View.OnClickListenertimeBtnListener =

33.newBtnOnClickListener(TIME_DIALOG);

34.ButtonbtnTime = (Button) findViewById(R.id.btnTime);

35.btnTime.setOnClickListener(timeBtnListener);

36.}

37.

38.

39.protectedDialog onCreateDialog(int id) {

40.//用来获取日期和时间的

41.Calendarcalendar = Calendar.getInstance();

42.

43.Dialogdialog = null;

44.switch(id){

45.caseDATE_DIALOG:

46.DatePickerDialog.OnDateSetListenerdateListener =

47.newDatePickerDialog.OnDateSetListener() {

48.@Override

49.publicvoid onDateSet(DatePicker datePicker,

50.int year,int month, int dayOfMonth) {

51.EditTexteditText =

52.(EditText)findViewById(R.id.editText);

53.//Calendar月份是从0开始,所以month要加1

54.editText.setText("你选择了" + year + "年" +

55.(month+1) + "月" + dayOfMonth + "日");

56.}

57.};

58.dialog =new DatePickerDialog(this,

59.dateListener,

60.calendar.get(Calendar.YEAR),

61.calendar.get(Calendar.MONTH),

62.calendar.get(Calendar.DAY_OF_MONTH));

63.break;

64.caseTIME_DIALOG:

65.TimePickerDialog.OnTimeSetListenertimeListener =

66.newTimePickerDialog.OnTimeSetListener() {

67.

68.@Override

69.publicvoid onTimeSet(TimePicker timerPicker,

70.inthourOfDay, int minute) {

71.EditTexteditText =

72.(EditText)findViewById(R.id.editText);

73.editText.setText("你选择了" + hourOfDay + "时" +

74.minute +"分");

75.}

76.};

77.dialog =new TimePickerDialog(this, timeListener,

78.calendar.get(Calendar.HOUR_OF_DAY),

79.calendar.get(Calendar.MINUTE),

80.false);//是否为二十四制

81.break;

82.default:

83.break;

84.}

85.returndialog;

86.}

87./*

88.* 成员内部类,此处为提高可重用性,也可以换成匿名内部类

89.*/

90.privateclass BtnOnClickListener implements View.OnClickListener {

91.

92.privateint dialogId = 0; //默认为0则不显示对话框

93.

94.publicBtnOnClickListener(int dialogId) {

95.this.dialogId= dialogId;

96.}

97.@Override

98.publicvoid onClick(View view) {

99.showDialog(dialogId);

100.}

101.

102.}

103.}

源码下载地址:http://download.csdn.net/source/3225379

分享到:

· 上一篇:18. android dialog —— 多选列表对话框

· 下一篇:20. android dialog——自定义对话框之一

20. android dialog——自定义对话框之一

分类: android入门2011-04-26 23:051459人阅读评论(2)收藏举报

还是先从最简单的开始吧,然后一步一步的扩展。

为了保证软件上所谓的低耦合度和可重用性,这里我不得不需要单独建立一个类CustomerDialog,然后继承AlertDialog

view plaincopy to clipboardprint?

1.publicclass CustomerDialog extends AlertDialog {}

然后添加一个带Context参数的构造器,context(上下文)通俗点讲一般是指归属于那个,这里就归属于调用的那个Acitivity,

也就是说这个对话框是针对调用的那个Activity

view plaincopy to clipboardprint?

1.publicCustomerDialog(Context context) {super(context);this.context = context;}

接下来需要对AlertDialog的 onCreate方法覆盖,否则在外面就无法获得你创建的那个自定义对话框的内容了(当然你也可以直接在构造方法里调用setView,当这样一来耦合度就增加了),然后把自己的自定义内容通过setView关联进去。

view plaincopy to clipboardprint?

1.@Overrideprotected voidonCreate(Bundle savedInstanceState) {TextView textView = newTextView(context);textView.setText("这是一个自定义对话框");textView.setTextSize(24);textView.setTextColor(Color.BLACK); setView(textView);super.onCreate(savedInstanceState);}

具体实现:

第一步:

res/layout/main.xml

定义一个button按钮,用来点击后弹出自定义对话框

view plaincopy to clipboardprint?

1.<?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 androidandroid:id="@+id/button"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="显示自定义对话框"/></LinearLayout>

第二步:创建自定义对话框类

src/com/dialog/ui/CustomerDialog.java

view plaincopy to clipboardprint?

1.packagecom.dialog.ui;import android.app.AlertDialog;importandroid.content.Context;import android.graphics.Color;import android.os.Bundle;importandroid.widget.TextView;public class CustomerDialog extends AlertDialog{private Context context = null;public CustomerDialog(Context context){super(context);this.context = context;}@Overrideprotectedvoid onCreate(Bundle savedInstanceState) {//此处仅一个简单的TextView,可以扩展到自定义xml里面TextViewtextView = new TextView(context);textView.setText("这是一个自定义对话框");textView.setTextSize(24);textView.setTextColor(Color.BLACK);setView(textView);super.onCreate(savedInstanceState);}}

第三步:在创建一个Activity

src/com/dialog/activity/CustomerDialogActivity.java

view plaincopy to clipboardprint?

1.packagecom.dialog.activity;import android.app.Activity;importandroid.app.Dialog;import android.os.Bundle;import android.view.View;importandroid.widget.Button;import com.dialog.ui.CustomerDialog;public classCustomerDialogActivity extends Activity {private final int CUSTOMER_DIALOG = 1; @Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.main); Buttonbutton = (Button) findViewById(R.id.button); View.OnClickListener listener =new View.OnClickListener() {@Overridepublicvoid onClick(View view){showDialog(CUSTOMER_DIALOG);}};button.setOnClickListener(listener); } @Override protected Dialog onCreateDialog(int id){ CustomerDialog dialog = null; switch(id) { case CUSTOMER_DIALOG: dialog = newCustomerDialog(CustomerDialogActivity.this); dialog.setTitle("自定义对话框");dialog.setIcon(R.drawable.icon); break; } return dialog; }}

上个丑陋的效果图(源码就不提供了)

接下来将继续扩展到自定义xml里面

分享到:

· 上一篇:19. android dialog —— 日期和时间选择对话框

· 下一篇:21. android dialog——自定义对话框之二

21. android dialog——自定义对话框之二

分类: android入门2011-04-27 23:06507人阅读评论(0)收藏举报

先建立一个layout,命名为customer_dialog.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="horizontal"

5.android:layout_width="fill_parent"

6.android:layout_height="wrap_content"

7.android:paddingRight="10dip"

8.android:paddingLeft="10dip">

9.<TextView android:id="@+id/userNameText"

10.android:layout_width="wrap_content"

11.android:layout_height="wrap_content"

12.android:textSize="18dip"

13.android:text="用户名:"

14.android:paddingRight="10dip"

15./>

16.<EditText android:id="@+id/userNameEditText"

17.android:text="输入用户名"

18.android:layout_width="fill_parent"

19.android:layout_height="wrap_content"

20.android:lines="1"

21./>

22.</LinearLayout>

然后在昨天的android dialog——自定义对话框之一 的修改onCreate方法,修改如下:

view plaincopy to clipboardprint?

1.@Override

2.protectedvoid onCreate(Bundle savedInstanceState) {

3.//关于LayoutInflate详解

4.//http://blog.csdn.net/jamesliulyc/archive/2011/04/14/6324432.aspx

5.LayoutInflaterinflater = LayoutInflater.from(context);

6.ViewcustomerLayout =

7.inflater.inflate(R.layout.customer_dialog,null);

8.setView(customerLayout);

9.super.onCreate(savedInstanceState);

10.}

关于LayoutInflate详解, 请参照 android Tab 选项卡控件 里的注释

以上就是在昨天的基础之上增加的自定义xml,其他任何代码都不用动了,很简单,接下来将继续添加事件监听

还是来个效果图吧,貌似比昨天的漂亮一点:

分享到:

· 上一篇:20. android dialog——自定义对话框之一

· 下一篇:Manufacturing Unique R.id Values(转)

23. android dialog——自定义对话框之三(带style的)

时间来不及,就贴代码了,另外顺便贴一下Activity模拟成一个Dialog,具体可以参考下面的网址

part1 http://blog.stylingandroid.com/archives/5

part2 http://blog.stylingandroid.com/archives/7

part3 http://blog.stylingandroid.com/archives/category/dialog-box

接下来是一个自定义对话框

第一步:

res/values/styles.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<style name="base">

4.<item name="android:padding">10dp</item>

5.</style>

6.<style name="title"parent="@style/base">

7.<item name="android:textColor">#FFFFFF</item>

8.<item name="android:textSize">16sp</item>

9.<item name="android:textStyle">bold</item>

10.<item name="android:background">#333333</item>

11.</style>

12.<style name="body" parent="@style/base">

13.<item name="android:textColor">#FFFFFF</item>

14.<item name="android:background">#666666</item>

15.</style>

16.

17.<style name="dialog"parent="@android:style/Theme.Dialog">

18.<item name="android:windowIsFloating">true</item>

19.<item name="android:windowNoTitle">true</item>

20.<item name="android:windowBackground">@null</item>

21.</style>

22.</resources>

第二步:

res/layout/customer_dialog.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

3.android:layout_width="wrap_content"

4.android:layout_height="wrap_content">

5.<TextView android:layout_width="match_parent"

6.android:id="@+id/title"

7.android:layout_alignParentTop="true"

8.android:layout_alignParentLeft="true"

9.android:layout_height="wrap_content"

10.style="@+style/title"

11.android:text="自定义对话框" />

12.<LinearLayout

13.xmlns:android="http://schemas.android.com/apk/res/android"

14.android:orientation="horizontal"

15.android:layout_alignLeft="@id/title"

16.android:layout_below="@id/title"

17.android:layout_width="fill_parent"

18.android:layout_height="wrap_content"

19.android:paddingRight="10dip"

20.android:paddingLeft="10dip"

21.android:id="@+id/body"

22.style="@+style/body"mce_style="@+style/body">

23.<TextView

24.android:layout_width="wrap_content"

25.android:layout_height="wrap_content"

26.android:textSize="18dip"

27.android:text="用户名:"

28.android:paddingRight="10dip"

29./>

30.<EditText android:id="@+id/username"

31.android:text="输入用户名"

32.android:layout_width="fill_parent"

33.android:layout_height="wrap_content"

34.android:lines="1"

35./>

36.</LinearLayout>

37.</RelativeLayout>

第三步:

res/layout/main.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

3.android:orientation="vertical"

4.android:layout_width="fill_parent"

5.android:layout_height="fill_parent"

6.>

7.<Button android:id="@+id/button"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:text="显示自定义对话框"

11./>

12.</LinearLayout>

第四步:

src/com/dialog/ui/CustomerDialog.java

view plaincopy to clipboardprint?

1.packagecom.dialog.ui;

2.

3.importandroid.app.AlertDialog;

4.importandroid.content.Context;

5.importandroid.os.Bundle;

6.importandroid.view.LayoutInflater;

7.importandroid.view.View;

8.

9.importcom.dialog.activity.R;

10.

11.publicclass CustomerDialog extends AlertDialog {

12.

13.publicCustomerDialog(Context context) {

14.super(context);

15.}

16.

17.publicCustomerDialog(Context context, int theme) {

18.super(context,theme);

19.}

20.

21.@Override

22.protectedvoid onCreate(Bundle savedInstanceState) {

23.//关于LayoutInflate详解

24.//http://blog.csdn.net/jamesliulyc/archive/2011/04/14/6324432.aspx

25.LayoutInflaterinflater = LayoutInflater.from(getContext());

26.ViewcustomerLayout =

27.inflater.inflate(R.layout.customer_dialog,null);

28.setView(customerLayout,0,0,0,0);

29.super.onCreate(savedInstanceState);

30.}

31.}

第五步:

src/com/dialog/activity/CustomerDialogActivity.java

view plaincopy to clipboardprint?

1.packagecom.dialog.activity;

2.

3.importandroid.app.Activity;

4.importandroid.app.Dialog;

5.importandroid.content.DialogInterface;

6.importandroid.os.Bundle;

7.importandroid.view.View;

8.importandroid.widget.Button;

9.importandroid.widget.Toast;

10.

11.importcom.dialog.ui.CustomerDialog;

12.

13.publicclass CustomerDialogActivity extends Activity {

14.

15.privatefinal int CUSTOMER_DIALOG = 1;

16.@Override

17.publicvoid onCreate(Bundle savedInstanceState) {

18.super.onCreate(savedInstanceState);

19.setContentView(R.layout.main);

20.

21.Buttonbutton = (Button) findViewById(R.id.button);

22.View.OnClickListenerlistener = new View.OnClickListener() {

23.

24.@Override

25.publicvoid onClick(View view) {

26.showDialog(CUSTOMER_DIALOG);

27.}

28.};

29.

30.button.setOnClickListener(listener);

31.}

32.

33.@Override

34.protectedDialog onCreateDialog(int id) {

35.CustomerDialogdialog = null;

36.switch(id){

37.caseCUSTOMER_DIALOG:

38.dialog =new CustomerDialog(CustomerDialogActivity.this,R.style.dialog);

39.DialogInterface.OnClickListenerlistener = new DialogInterface.OnClickListener() {

40.

41.@Override

42.publicvoid onClick(DialogInterface dialog, int which) {

43.Toast.makeText(CustomerDialogActivity.this,

44."这是一个自定义对话框",Toast.LENGTH_LONG).show();

45.}

46.};

47.dialog.setButton("确定", listener);

48.dialog.setButton2("取消", listener);

49.break;

50.}

51.

52.returndialog;

53.}

54.}

效果图:

分享到:

· 上一篇:Manufacturing Unique R.id Values(转)

· 下一篇:24. android dialog ——ProgressDialog 进度条对话框详解

24. android dialog ——ProgressDialog 进度条对话框详解

首先在onCreateDialog方法里创建一个ProgressDialog,如下:

view plaincopy to clipboardprint?

1.//this表示该对话框是针对当前Activity的

2.progressDialog= new ProgressDialog(this);

3.//设置最大值为100

4.progressDialog.setMax(100);

5.//设置进度条风格STYLE_HORIZONTAL

6.progressDialog.setProgressStyle(

7.ProgressDialog.STYLE_HORIZONTAL);

8.progressDialog.setTitle("进度条对话框");

接下来就是进度条的进度更新,因为对话框对象一直被当前Dialog保存着,所以onCreateDialog在下次调用对话框时不会在被调,所以

进度条更新操作不能在onCreateDialog里面,而是在onPrepareDialog里面进行。

首先要将进度条置为0

view plaincopy to clipboardprint?

1.progressDialog.incrementProgressBy(-progressDialog.getProgress());

increamentProgressBy源码中是调用了ProgressBar的setProgress(mProgress + diff);mProgress是当前进度值,这里的diff就是-progressDialog.getProgress(),最后结果为0,所以也可以这么用,效果和调用incrementProgressBy一样的,如下:

view plaincopy to clipboardprint?

1.progressDialog.onStart();

2.progressDialog.setProgress(0);

值得一提的是,不能直接只用setProgress(0)来设置,这样的话,第一次弹出对话框效果可以和上面的一样,但是之后再弹出对话框的进度一直都是100。为什么这里不能直接用setProgress(0),查看源码可以知道,

view plaincopy to clipboardprint?

1.if(mHasStarted) {

2.mProgress.setProgress(value);

3.onProgressChanged();

4.} else {

5.mProgressVal= value;

6.}

mHasStarted第一次调用的时候是true,当进度条达到100%时会调用onStop方法(此方法为protected,无法直接调用),将mHasStarted设置为false,也就是无法setProgress(value)了,只能通过onStart来将mHasStarted设置为true。

当点击“显示进度条对话框”按钮,这时候需要很耗时然后才显示对话框,而往往都会导致假死,如果超过5秒未响应将强制关闭,所以这里需要添加个多线程来做进一步处理。而进度条的增加效果是很快的,所以这这里需要让大家看到效果,得停几毫秒后再继续。

为了使主线程不受影响(处理当前Activity的线程),在点击按钮且耗时操作完后需要发送消息给主线程,主线程再做相应处理。线程之间的消息传递和异步处理是通过Handler来做处理的,相关代码如下:

view plaincopy to clipboardprint?

1.newThread() {

2.publicvoid run() {

3.for(inti=0; i<=100;i++) {

4.handler.sendEmptyMessage(INCREASE);

5.if(progressDialog.getProgress()>= 100) {

6.break;

7.}

8.try {

9.Thread.sleep(50);

10.} catch(InterruptedException e) {

11.e.printStackTrace();

12.}

13.}

14.}

15.}.start();

Handler的处理如下:(Handler具体说明网上很多,可以参考此处 http://my.unix-center.net/~Simon_fu/?p=652

view plaincopy to clipboardprint?

1.handler =new Handler() {

2.@Override

3.publicvoid handleMessage(Message msg) {

4.switch(msg.what){

5.caseINCREASE:

6.progressDialog.incrementProgressBy(1);

7.if(progressDialog.getProgress()>= 100) {

8.//progressDialog.dismiss();

9.}

10.break;

11.}

12.super.handleMessage(msg);

13.}

14.};

解释就到这里,先看个效果图:

实现步骤:

第一步,一个按钮用来点击后弹出对话框的

res/layout/progress_dialog_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:layout_width="fill_parent"

5.android:layout_height="wrap_content">

6.<Button android:id="@+id/button"

7.android:text="显示进度条对话框"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"/>

10.</LinearLayout>

第二步,

src/com/dialog/activity/ProgressDialogActivity.java

view plaincopy to clipboardprint?

1.packagecom.dialog.activity;

2.

3.importandroid.app.Activity;

4.importandroid.app.Dialog;

5.importandroid.app.ProgressDialog;

6.importandroid.os.Bundle;

7.importandroid.os.Handler;

8.importandroid.os.Message;

9.importandroid.view.View;

10.importandroid.widget.Button;

11.

12.publicclass ProgressDialogActivity extends Activity {

13.

14.privatefinal int PROGRESS_DIALOG = 1;

15.

16.privatefinal int INCREASE = 0;

17.

18.privateProgressDialog progressDialog = null;

19.

20.privateHandler handler = null;

21.

22.@Override

23.publicvoid onCreate(Bundle savedInstanceState) {

24.super.onCreate(savedInstanceState);

25.setContentView(R.layout.progress_dialog_layout);

26.

27.Buttonbutton = (Button) findViewById(R.id.button);

28.View.OnClickListenerlistener =

29.newView.OnClickListener() {

30.

31.@Override

32.publicvoid onClick(View view) {

33.showDialog(PROGRESS_DIALOG);

34.}

35.};

36.button.setOnClickListener(listener);

37.

38.handler =new Handler() {

39.@Override

40.publicvoid handleMessage(Message msg) {

41.switch(msg.what){

42.caseINCREASE:

43.progressDialog.incrementProgressBy(1);

44.if(progressDialog.getProgress()>= 100) {

45.//progressDialog.dismiss();

46.}

47.break;

48.}

49.super.handleMessage(msg);

50.}

51.};

52.}

53.

54.@Override

55.publicDialog onCreateDialog(int id) {

56.switch(id){

57.casePROGRESS_DIALOG:

58.//this表示该对话框是针对当前Activity的

59.progressDialog= new ProgressDialog(this);

60.//设置最大值为100

61.progressDialog.setMax(100);

62.//设置进度条风格STYLE_HORIZONTAL

63.progressDialog.setProgressStyle(

64.ProgressDialog.STYLE_HORIZONTAL);

65.progressDialog.setTitle("进度条对话框");

66.break;

67.}

68.returnprogressDialog;

69.}

70.

71.@Override

72.publicvoid onPrepareDialog(int id, Dialog dialog) {

73.

74.switch(id){

75.casePROGRESS_DIALOG:

76.//将进度条清0

77.progressDialog.incrementProgressBy(-progressDialog.getProgress());

78.newThread() {

79.publicvoid run() {

80.for(inti=0; i<=100;i++) {

81.handler.sendEmptyMessage(INCREASE);

82.if(progressDialog.getProgress()>= 100) {

83.break;

84.}

85.try {

86.Thread.sleep(50);

87.} catch(InterruptedException e) {

88.e.printStackTrace();

89.}

90.}

91.}

92.}.start();

93.break;

94.}

95.}

96.}

源码下载地址:http://download.csdn.net/source/3244868

25. android Toast 带图片的消息提示

实现Toast只需要两句话,第一是声明一个Toast,第二是显示这个Toast,如下:

view plaincopy to clipboardprint?

1.Toast toast = Toast.makeText(ToastActivity.this,

2."带图片的Toast",Toast.LENGTH_LONG);

3.toast.show();

makeText第一个参数是指对针对那个上下文的,这里是针对当前这个Activity的消息提示,第二个参数是要显示的文字,第三个参数显示的时间,过了这个时间后会消失。

接下来是在此基础之上加个图片,首先定义一个ImageView,然后Toast也有个View,需要对ImageView和Toast的View合并到一个Layout里面,然后替换掉Toast的View.具体如下:

view plaincopy to clipboardprint?

1.//定义一个ImageView

2.ImageViewimageView = new ImageView(ToastActivity.this);

3.imageView.setImageResource(R.drawable.icon);

4.

5.//获得Toast的View

6.ViewtoastView = toast.getView();

7.

8.//定义一个Layout,这里是Layout

9.LinearLayoutlinearLayout =

10.newLinearLayout(ToastActivity.this);

11.linearLayout.setOrientation(LinearLayout.HORIZONTAL);

12.

13.//将ImageView和ToastView合并到Layout中

14.linearLayout.addView(imageView);

15.linearLayout.addView(toastView);

16.

17.//替换掉原有的ToastView

18.toast.setView(linearLayout);

贴个效果图:

具体实现步骤:

第一步:定义一个button用来点击后弹出消息提示

res/layout/toast_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:layout_width="fill_parent"

5.android:layout_height="wrap_content">

6.<Button

7.android:id="@+id/button"

8.android:text="显示消息提示"

9.android:layout_width="fill_parent"

10.android:layout_height="wrap_content"

11./>

12.</LinearLayout>

第二步:

src/com/mytoast/activity/ToastActivity.java

view plaincopy to clipboardprint?

1.packagecom.mytoast.activity;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.importandroid.view.View;

6.importandroid.widget.Button;

7.importandroid.widget.ImageView;

8.importandroid.widget.LinearLayout;

9.importandroid.widget.Toast;

10.

11.publicclass ToastActivity extends Activity {

12.@Override

13.publicvoid onCreate(Bundle savedInstanceState) {

14.super.onCreate(savedInstanceState);

15.setContentView(R.layout.toast_layout);

16.

17.Buttonbutton = (Button) findViewById(R.id.button);

18.View.OnClickListenerlistener = new View.OnClickListener() {

19.

20.@Override

21.publicvoid onClick(View view) {

22.//先定义一个Toast

23.Toasttoast = Toast.makeText(ToastActivity.this,

24."带图片的Toast",Toast.LENGTH_LONG);

25.//定义一个ImageView

26.ImageViewimageView = new ImageView(ToastActivity.this);

27.imageView.setImageResource(R.drawable.icon);

28.

29.//获得Toast的View

30.ViewtoastView = toast.getView();

31.

32.//定义一个Layout,这里是Layout

33.LinearLayoutlinearLayout =

34.newLinearLayout(ToastActivity.this);

35.linearLayout.setOrientation(LinearLayout.HORIZONTAL);

36.

37.//将ImageView和ToastView合并到Layout中

38.linearLayout.addView(imageView);

39.linearLayout.addView(toastView);

40.

41.//替换掉原有的ToastView

42.toast.setView(linearLayout);

43.toast.show();

44.}

45.};

46.

47.button.setOnClickListener(listener);

48.}

49.}

因为这个很简单,所以源码不提供了,照着上面写就出来了。

分享到:

· 上一篇:24. android dialog ——ProgressDialog 进度条对话框详解

· 下一篇:26. android Notification 状态栏通知

26. android Notification 状态栏通知

首先声明一个Notification,然后定义一个getSystemService来获得NotificationManager服务对象

view plaincopy to clipboardprint?

1.Notificationnoticed = new Notification();

2.NotificationManagernoticedManager =

3.(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

4.noticedManager.notify(0, noticed);

然后通过点击消息通知跳转到另外一个Activity里,如下:

view plaincopy to clipboardprint?

1.Intentintent = new Intent(MainActivity.this,

2.NotificationActivity.class);

3.PendingIntentpending = PendingIntent.getActivity(MainActivity.this,

4.0, intent, 0);

5.

6.Notificationnoticed = new Notification();

7.noticed.icon= R.drawable.icon;

8.noticed.tickerText= "状态栏通知";

9.noticed.defaults= Notification.DEFAULT_SOUND;

10.noticed.setLatestEventInfo(MainActivity.this,

11."这是一个状态栏通知", "查看", pending);

12.NotificationManagernoticedManager =

13.(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

14.noticedManager.notify(0, noticed);

整个步骤如下:

第一步:

定义一个layout,一个按钮用来单击后出现状态栏通知,

res/layout/main.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

3.android:orientation="vertical"

4.android:layout_width="fill_parent"

5.android:layout_height="fill_parent"

6.>

7.<Button android:layout_width="fill_parent"

8.android:layout_height="wrap_content"

9.android:id="@+id/button"

10.android:text="显示消息提示"/>

11.</LinearLayout>

第二步:

由状态通知栏跳转到

res/layout/notification_layout.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:layout_width="fill_parent"

5.android:layout_height="wrap_content">

6.<EditText

7.android:text="启动Notification"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:editable="false"

11.android:cursorVisible="false"

12.android:layout_gravity="center_horizontal"

13./>

14.</LinearLayout>

第三步:

src/com/notification/activity/MainActivity.java

view plaincopy to clipboardprint?

1.packagecom.notification.activity;

2.

3.importandroid.app.Activity;

4.importandroid.app.Notification;

5.importandroid.app.NotificationManager;

6.importandroid.app.PendingIntent;

7.importandroid.content.Intent;

8.importandroid.os.Bundle;

9.importandroid.view.View;

10.importandroid.widget.Button;

11.

12.publicclass MainActivity extends Activity {

13.@Override

14.publicvoid onCreate(Bundle savedInstanceState) {

15.super.onCreate(savedInstanceState);

16.setContentView(R.layout.main);

17.

18.Buttonbutton = (Button) findViewById(R.id.button);

19.View.OnClickListenerlistener = new View.OnClickListener() {

20.

21.@Override

22.publicvoid onClick(View view) {

23.Intentintent = new Intent(MainActivity.this,

24.NotificationActivity.class);

25.PendingIntentpending = PendingIntent.getActivity(MainActivity.this,

26.0, intent, 0);

27.

28.Notificationnoticed = new Notification();

29.noticed.icon= R.drawable.icon;

30.noticed.tickerText= "状态栏通知";

31.noticed.defaults= Notification.DEFAULT_SOUND;

32.noticed.setLatestEventInfo(MainActivity.this,

33."这是一个状态栏通知", "查看", pending);

34.NotificationManagernoticedManager =

35.(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

36.noticedManager.notify(0, noticed);

37.}

38.};

39.button.setOnClickListener(listener);

40.}

41.}

第四步:

src/com/notification/activity/NotificationActivity.java

view plaincopy to clipboardprint?

1.packagecom.notification.activity;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.

6.publicclass NotificationActivity extends Activity {

7.

8.@Override

9.publicvoid onCreate(Bundle savedInstanceState) {

10.super.onCreate(savedInstanceState);

11.setContentView(R.layout.notification_layout);

12.}

13.}

第五步:

AndroidManifest.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3.package="com.notification.activity"

4.android:versionCode="1"

5.android:versionName="1.0">

6.<application android:icon="@drawable/icon"android:label="@string/app_name">

7.<activity android:name=".MainActivity"

8.android:label="@string/app_name">

9.<intent-filter>

10.<action android:name="android.intent.action.MAIN"/>

11.<category android:name="android.intent.category.LAUNCHER"/>

12.</intent-filter>

13.</activity>

14.<activity android:name=".NotificationActivity"/>

15.</application>

16.<uses-sdk android:minSdkVersion="8"/>

17.

18.</manifest>

效果图:

分享到:

· 上一篇:25. android Toast 带图片的消息提示

· 下一篇:27. BroadcastReceiver 消息广播详解----简单监控拨打电话

27. BroadcastReceiver 消息广播详解----简单监控拨打电话

当拨打电话时,拨打电话程序会向系统发生消息,来告诉系统自己在干嘛,这里就是所谓的广播,这样做是为了方便跟其他应用程序或者底层沟通。那么如何才能让其他应用程序拿到这个消息(广播),这里就需要借助广播接收者BroadcastReceiver这个类。

BroadcastReceiver的onReceiver方法用来接收广播,当一个程序安装到系统的时候,会注册到系统中,这样就能得到系统中的各种广播或者其他有信息,然后与其他程序打交道。过滤到自己想要的广播得指定IntentFilter特定的action,还得是否有这个权限读到这个广播消息,并且必须对该广播接收者进行注册。以下是实现方式:

第一种实现方式,写在AndroidManifest.xml里

view plaincopy to clipboardprint?

1.<receiver android:name=".MyReceiver">

2.<intent-filter>

3.<action android:name="android.intent.action.PHONE_STATE"/>

4.</intent-filter>

5.</receiver>

第二种方式是在java代码里

view plaincopy to clipboardprint?

1.MyReceivermyReceiver = new MyReceiver();

2.IntentFilterfilter = new IntentFilter();

3.filter.addAction("android.intent.action.PHONE_STATE");

4.registerReceiver(myReceiver,filter);

另外需要加上权限控制:

view plaincopy to clipboardprint?

1.<uses-permission android:name="android.permission.READ_PHONE_STATE">

2.</uses-permission>

具体步骤实现如下:

第一步:

先画一个按钮,然后通过点击这个按钮退出程序,这里只是为了让该程序安装到手机或者模拟器里

/BroadcastReceiverDemo/res/layout/main.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

3.android:orientation="vertical"

4.android:layout_width="fill_parent"

5.android:layout_height="fill_parent"

6.>

7.<Button android:id="@+id/button"

8.android:layout_width="fill_parent"

9.android:layout_height="wrap_content"

10.android:text="启动BroadcastReceiver"/>

11.

12.</LinearLayout>

第二步:

对main.xml里的按钮进行事件监听,单击后退出程序

/BroadcastReceiverDemo/src/com/broadcast/activity/MainActivity.java

view plaincopy to clipboardprint?

1.packagecom.broadcast.activity;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.importandroid.view.View;

6.importandroid.widget.Button;

7.

8.publicclass MainActivity extends Activity {

9.

10.@Override

11.publicvoid onCreate(Bundle savedInstanceState) {

12.super.onCreate(savedInstanceState);

13.setContentView(R.layout.main);

14.

15.Buttonbutton = (Button) findViewById(R.id.button);

16.View.OnClickListenerlistener = new View.OnClickListener() {

17.

18.@Override

19.publicvoid onClick(View v) {

20.System.exit(0);

21.}

22.};

23.

24.button.setOnClickListener(listener);

25.}

26.}

第三步:

定义一个广播接收者

/BroadcastReceiverDemo/src/com/broadcast/activity/MyReceiver.java

view plaincopy to clipboardprint?

1.packagecom.broadcast.activity;

2.

3.importandroid.content.BroadcastReceiver;

4.importandroid.content.Context;

5.importandroid.content.Intent;

6.

7.publicclass MyReceiver extends BroadcastReceiver {

8.

9.//这里intent是来自于拨打电话,而intentTemp是用来跳转到MainActivity界面里

10.@Override

11.publicvoid onReceive(Context context, Intent intent) {

12.IntentintentTemp = new Intent(context, MainActivity.class);

13.//必须为这个intent设置一个Flag

14.intentTemp.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

15.context.startActivity(intentTemp);

16.}

17.}

第四步:注册MyReceiver,并开启相关权限

/BroadcastReceiverDemo/AndroidManifest.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<manifest xmlns:android="http://schemas.android.com/apk/res/android"

3.package="com.broadcast.activity"

4.android:versionCode="1"

5.android:versionName="1.0">

6.<application android:icon="@drawable/icon"android:label="@string/app_name">

7.<activity android:name=".MainActivity"

8.android:label="@string/app_name">

9.<intent-filter>

10.<action android:name="android.intent.action.MAIN"/>

11.<category android:name="android.intent.category.LAUNCHER"/>

12.</intent-filter>

13.</activity>

14.<receiver android:name=".MyReceiver">

15.<intent-filter>

16.<!-- 得到电话状态广播,可以得到拨打电话-->

17.<action android:name="android.intent.action.PHONE_STATE"/> </intent-filter>

18.</receiver>

19.</application>

20.<uses-sdk android:minSdkVersion="8"/>

21.<!-- 设置该程序能够读取到电话状态-->

22.<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

23.</manifest>

操作步骤:

运行该程序,然后点击按钮后会关闭该程序(表示已经安装到系统),然后拨打电话,接下来该程序界面又会出现。

分享到:

· 上一篇:26. android Notification 状态栏通知

· 下一篇:1. android 背景渐变色(shape,gradient)

28. android——miniTwitter登录界面 详解

先上个图:

布局分析:分成三个部分,该Activity是一个无标题的,设置无标题需要在setContentView之前设置,否则会报错,

view plaincopy to clipboardprint?

1.requestWindowFeature(Window.FEATURE_NO_TITLE);

2.setContentView(R.layout.login);

第一部分是一个带渐变色背景的LinearLayout布局,关于背景渐变色请参照 android小技巧:android 背景渐变色(shape,gradient)

这里就不再贴上代码了,效果如下图所示

第二部分,红色线区域内,包括1,2,3,4 如图所示:

红色的1表示的是一个带圆角且背景色为#55FFFFFF(淡蓝色)的RelativeLayout布局,代码如下

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="UTF-8"?>

2.<shape xmlns:android="http://schemas.android.com/apk/res/android">

3.<solid android:color="#55FFFFFF"/>

4.<!-- 设置圆角

5.注意:bottomRightRadius是左下角而不是右下角bottomLeftRadius右下角-->

6.<corners android:topLeftRadius="10dp"android:topRightRadius="10dp"

7.android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp"/>

8.</shape>

solid表示填充色,这里填充的是淡蓝色。 corners是设置圆角。

dp (即dip,device independent pixels)设备独立像素:这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA ,不依赖像素。 在android上开发的程序将会在不同分辨率的手机上运行。为了让程序外观不至于相差太大,所以引入了dip的概念。比如定义一个矩形10 x 10dip. 在分辨率为160dpi 的屏上,比如G1,正好是10 x 10像素。 而在240 dpi 的屏,则是15 x 15 像素. 换算公式为 pixs = dips * (density/160). density 就是屏的分辨率

然后RelativeLayou的background引用此drawable,具体RelativeLayout设置如下

view plaincopy to clipboardprint?

1.<RelativeLayout

2.android:id="@+id/login_div"

3.android:layout_width="fill_parent"

4.android:layout_height="wrap_content"

5.android:padding="15dip"

6.android:layout_margin="15dip"

7.android:background="@drawable/background_login_div_bg"

8.>

9.</RelativeLayout>

padding 是指内边距(也就是指内容与边框的距离), layout_margin为外边距(它的上一层与边框的距离)。

接下来是区域2,为账号的文本和输入框,首先是账号的文本,代码如下:

view plaincopy to clipboardprint?

1.<TextView

2.android:id="@+id/login_user_input"

3.android:layout_width="wrap_content"

4.android:layout_height="wrap_content"

5.android:layout_alignParentTop="true"

6.android:layout_marginTop="5dp"

7.android:text="@string/login_label_username"

8.style="@style/normalText"/>

android:layout_alignParentTop 这里表示此TextView的位置处于顶部

android:layout_marginTop="5dp"这里表示此TextView的边框与RelativeLayout的顶部边框距离有5dp

这里需要对这个TextView设置下字体颜色和字体大小,定义在res/style.xml里面

view plaincopy to clipboardprint?

1.<style name="normalText"parent="@android:style/TextAppearance">

2.<item name="android:textColor">#444</item>

3.<item name="android:textSize">14sp</item>

4.</style>


定义账号的输入框,如下

view plaincopy to clipboardprint?

1.<EditText

2.android:id="@+id/username_edit"

3.android:layout_width="fill_parent"

4.android:layout_height="wrap_content"

5.android:hint="@string/login_username_hint"

6.android:layout_below="@id/login_user_input"

7.android:singleLine="true"

8.android:inputType="text"/>

android:hint 输入框里面的提示文字,

android:layout_below这里是设置为在账号的文本框的下面,

android:singleLine 为单行输入(即你输入回车的时候不会在换行了)

android:inputType这里text表示 输入的类型为文本

区域3是密码文本和输入框,同区域2,代码如下:

view plaincopy to clipboardprint?

1.<TextView

2.android:id="@+id/login_password_input"

3.android:layout_width="wrap_content"

4.android:layout_height="wrap_content"

5.android:layout_below="@id/username_edit"

6.android:layout_marginTop="3dp"

7.android:text="@string/login_label_password"

8.style="@style/normalText"/>

9.<EditText

10.android:id="@+id/password_edit"

11.android:layout_width="fill_parent"

12.android:layout_height="wrap_content"

13.android:layout_below="@id/login_password_input"

14.android:password="true"

15.android:singleLine="true"

16.android:inputType="textPassword"

17./>

区域4,登录按钮

view plaincopy to clipboardprint?

1.<Button

2.android:id="@+id/signin_button"

3.android:layout_width="wrap_content"

4.android:layout_height="wrap_content"

5.android:layout_below="@id/password_edit"

6.android:layout_alignRight="@id/password_edit"

7.android:text="@string/login_label_signin"

8.android:background="@drawable/blue_button"

9./>

第三部分:底下的文字和两张图片,分别标记了1,2,3,4

区域1:还是一个RelativeLayout,但这里设置的很简单,代码如下:

view plaincopy to clipboardprint?

1.<RelativeLayout

2.android:layout_width="fill_parent"

3.android:layout_height="wrap_content">

4.lt;/RelativeLayout>

区域2:"没有账号?注册"这几个文字定义在string里面,包含了一个<a>标签,

view plaincopy to clipboardprint?

1.<string name="login_register_link">没有帐号? <a href="#"mce_href="#">注册</a></string>

定义如下:

view plaincopy to clipboardprint?

1.<TextView android:id="@+id/register_link"

2.android:text="@string/login_register_link"

3.android:layout_width="wrap_content"

4.android:layout_height="wrap_content"

5.android:layout_marginLeft="15dp"

6.android:textColor="#888"

7.android:textColorLink="#FF0066CC"

8./>

TextView是支持简单的html标签的,如<a>标签,但并不是支持所有标签,支持更复杂的html标签得用webView组件。

android:textColorLink是设置文字链接的颜色. 虽然TextView支持<a>标签,但是这里是不能点此链接的,不要被假象迷惑。

区域3是一直猫的卡通图片,貌似有点丑,将就下吧,

view plaincopy to clipboardprint?

1.<ImageViewandroid:id="@+id/miniTwitter_logo"

2.android:src="@drawable/cat"

3.android:layout_width="wrap_content"

4.android:layout_height="wrap_content"

5.android:layout_alignParentRight="true"

6.android:layout_alignParentBottom="true"

7.android:layout_marginRight="25dp"

8.android:layout_marginLeft="10dp"

9.android:layout_marginBottom="25dp"

10./>

android:layout_alignParentRight="true"位于layout的最右边

android:layout_alignParentBottom="true"位于layout的最底部

android:layout_marginRight="25dp"该imageView的边框距离layout边框有25dp,其他的margin类似。

区域4 是一个带文字的图片的ImageView,

view plaincopy to clipboardprint?

1.<ImageView android:src="@drawable/logo"

2.android:layout_width="wrap_content"

3.android:layout_height="wrap_content"

4.android:layout_toLeftOf="@id/miniTwitter_logo"

5.android:layout_alignBottom="@id/miniTwitter_logo"

6.android:paddingBottom="8dp"

7./>

android:layout_toLeftOf="@id/miniTwitter_logo"在那个小猫ImageView的左边(水平位置)

android:layout_alignBottom="@id/miniTwitter_logo"这里意思是这两个ImageView(区域3和区域4)下边缘对齐

android:paddingBottom="8dp"图片距离ImageView底部边框8dp,也就是将图片上抬个8dp

具体步骤如下:

第一步:一些字符串定义

/miniTwitterLoginDemo/res/values/strings.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<string name="hello">Hello World, LoginActivity!</string>

4.<string name="login_label_username">帐号</string>

5.<string name="login_label_password">密码</string>

6.<string name="login_label_signin">登 录</string>

7.<string name="login_status_logging_in">登录中...</string>

8.<string name="login_username_hint">Email或手机号</string>

9.<string name="login_register_link">没有帐号? <a href="#"mce_href="#">注册</a></string>

10.<string name="app_name">miniTwitter</string>

11.</resources>

第二步:

/miniTwitterLoginDemo/res/values/style.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<resources>

3.<style name="normalText"parent="@android:style/TextAppearance"> <itemname="android:textColor">#444</item>

4.<item name="android:textSize">14sp</item>

5.</style>

6.</resources>

第三步:背景色为渐变色

/miniTwitterLoginDemo/res/drawable-mdpi/background_login.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<shape xmlns:android="http://schemas.android.com/apk/res/android">

3.<gradient

4.android:startColor="#FFACDAE5"

5.android:endColor="#FF72CAE1"

6.android:angle="45"

7./>

8.</shape>

第四步:背景色味淡蓝色且为圆角

/miniTwitterLoginDemo/res/drawable-mdpi/background_login_div_bg.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="UTF-8"?>

2.<shape xmlns:android="http://schemas.android.com/apk/res/android">

3.<solid android:color="#55FFFFFF"/>

4.<!-- 设置圆角

5.注意:bottomRightRadius是左下角而不是右下角bottomLeftRadius右下角-->

6.<corners android:topLeftRadius="10dp"android:topRightRadius="10dp"

7.android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp"/>

8.</shape>

第五步:

/miniTwitterLoginDemo/res/layout/login.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="fill_parent"

7.android:background="@drawable/background_login">

8.<!--padding 内边距layout_margin 外边距

9.android:layout_alignParentTop布局的位置是否处于顶部 -->

10.<RelativeLayout

11.android:id="@+id/login_div"

12.android:layout_width="fill_parent"

13.android:layout_height="wrap_content"

14.android:padding="15dip"

15.android:layout_margin="15dip"

16.android:background="@drawable/background_login_div_bg"

17.>

18.<!-- 账号 -->

19.<TextView

20.android:id="@+id/login_user_input"

21.android:layout_width="wrap_content"

22.android:layout_height="wrap_content"

23.android:layout_alignParentTop="true"

24.android:layout_marginTop="5dp"

25.android:text="@string/login_label_username"

26.style="@style/normalText"/>

27.<EditText

28.android:id="@+id/username_edit"

29.android:layout_width="fill_parent"

30.android:layout_height="wrap_content"

31.android:hint="@string/login_username_hint"

32.android:layout_below="@id/login_user_input"

33.android:singleLine="true"

34.android:inputType="text"/>

35.<!-- 密码 text -->

36.<TextView

37.android:id="@+id/login_password_input"

38.android:layout_width="wrap_content"

39.android:layout_height="wrap_content"

40.android:layout_below="@id/username_edit"

41.android:layout_marginTop="3dp"

42.android:text="@string/login_label_password"

43.style="@style/normalText"/>

44.<EditText

45.android:id="@+id/password_edit"

46.android:layout_width="fill_parent"

47.android:layout_height="wrap_content"

48.android:layout_below="@id/login_password_input"

49.android:password="true"

50.android:singleLine="true"

51.android:inputType="textPassword"

52./>

53.<!-- 登录button -->

54.<Button

55.android:id="@+id/signin_button"

56.android:layout_width="wrap_content"

57.android:layout_height="wrap_content"

58.android:layout_below="@id/password_edit"

59.android:layout_alignRight="@id/password_edit"

60.android:text="@string/login_label_signin"

61.android:background="@drawable/blue_button"

62./>

63.</RelativeLayout>

64.

65.

66.<RelativeLayout

67.android:layout_width="fill_parent"

68.android:layout_height="wrap_content"

69.>

70.<TextView android:id="@+id/register_link"

71.android:text="@string/login_register_link"

72.android:layout_width="wrap_content"

73.android:layout_height="wrap_content"

74.android:layout_marginLeft="15dp"

75.android:textColor="#888"

76.android:textColorLink="#FF0066CC"

77./>

78.<ImageView android:id="@+id/miniTwitter_logo"

79.android:src="@drawable/cat"

80.android:layout_width="wrap_content"

81.android:layout_height="wrap_content"

82.android:layout_alignParentRight="true"

83.android:layout_alignParentBottom="true"

84.android:layout_marginRight="25dp"

85.android:layout_marginLeft="10dp"

86.android:layout_marginBottom="25dp"

87./>

88.<ImageView android:src="@drawable/logo"

89.android:layout_width="wrap_content"

90.android:layout_height="wrap_content"

91.android:layout_toLeftOf="@id/miniTwitter_logo"

92.android:layout_alignBottom="@id/miniTwitter_logo"

93.android:paddingBottom="8dp"

94./>

95.</RelativeLayout>

96.

97.</LinearLayout>

第七步:

/miniTwitterLoginDemo/src/com/mytwitter/acitivity/LoginActivity.java

view plaincopy to clipboardprint?

1.packagecom.mytwitter.acitivity;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.importandroid.view.Window;

6.

7.publicclass LoginActivity extends Activity {

8.@Override

9.publicvoid onCreate(Bundle savedInstanceState) {

10.super.onCreate(savedInstanceState);

11.requestWindowFeature(Window.FEATURE_NO_TITLE);

12.setContentView(R.layout.login);

13.}

14.}

到这里就解释结束了。

源代码下载地址:http://download.csdn.net/source/3300067

分享到:

· 上一篇:1. android 背景渐变色(shape,gradient)

· 下一篇:2. android 边框圆角

1、android 模拟小球来回撞墙效果(游戏的开始)

分类: android 高级2011-07-05 15:44127人阅读评论(4)收藏举报

先将代码贴一下

view plaincopy to clipboardprint?

1.packagecom.ball;

2.

3.importandroid.app.Activity;

4.importandroid.os.Bundle;

5.importandroid.view.Window;

6.importandroid.view.WindowManager;

7.

8.publicclass MainActivity extends Activity {

9.@Override

10.publicvoid onCreate(Bundle savedInstanceState) {

11.super.onCreate(savedInstanceState);

12.requestWindowFeature(Window.FEATURE_NO_TITLE);

13.getWindow().setFlags(//设置为全屏模式

14.WindowManager.LayoutParams.FLAG_FULLSCREEN,

15.WindowManager.LayoutParams.FLAG_FULLSCREEN);

16.setContentView(newBallView(this));

17.}

18.}

view plaincopy to clipboardprint?

1.packagecom.ball;

2.

3.importandroid.content.Context;

4.importandroid.content.res.Resources;

5.importandroid.graphics.Bitmap;

6.importandroid.graphics.BitmapFactory;

7.importandroid.graphics.Canvas;

8.importandroid.view.SurfaceHolder;

9.importandroid.view.SurfaceView;

10.

11.

12.publicclass BallView extends SurfaceView implements SurfaceHolder.Callback {

13.

14.BitmapbitmapBall = null;

15.Movablemovable = null;

16.DrawThreaddt;

17.BitmapbmpBack;

18.

19.publicBallView(Context context) {

20.super(context);

21.getHolder().addCallback(this);

22.initBitmaps(getResources());

23.initMovable();

24.dt = newDrawThread(this,getHolder());

25.}

26.

27.publicvoid initBitmaps(Resources r) {

28.bitmapBall= BitmapFactory.decodeResource(r, R.drawable.icon);

29.}

30.

31.publicvoid initMovable() {

32.movable =new Movable(0,0,

33.0, bitmapBall);

34.}

35.

36.publicvoid doDraw(Canvas canvas) {

37.int color= getResources().getColor(android.R.color.white);

38.canvas.drawColor(color);

39.movable.drawSelf(canvas);

40.}

41.

42.@Override

43.publicvoid surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

44.}

45.

46.@Override

47.publicvoid surfaceCreated(SurfaceHolder holder) {

48.if(!dt.isAlive()){

49.dt.start();

50.}

51.}

52.

53.@Override

54.publicvoid surfaceDestroyed(SurfaceHolder holder) {

55.dt.flag =false;

56.dt =null;

57.}

58.

59.}

view plaincopy to clipboardprint?

1.packagecom.ball;

2.

3.importandroid.graphics.Canvas;

4.importandroid.view.SurfaceHolder;

5.

6.publicclass DrawThread extends Thread {

7.booleanflag = false;

8.BallViewballView;

9.SurfaceHoldersurfaceHolder;

10.intsleepSpan = 30;

11.

12.publicDrawThread(BallView ballView, SurfaceHolder surfaceHolder) {

13.this.ballView= ballView;

14.this.surfaceHolder= surfaceHolder;

15.this.flag= true;

16.}

17.

18.publicvoid run() {

19.Canvascanvas = null;

20.while(flag){

21.try {

22.canvas =surfaceHolder.lockCanvas(null);

23.synchronized(surfaceHolder){

24.ballView.doDraw(canvas);

25.}

26.}catch(Exception e) {

27.e.printStackTrace();

28.} finally{

29.if(canvas!= null) {

30.surfaceHolder.unlockCanvasAndPost(canvas);

31.}

32.}

33.

34.try{

35.Thread.sleep(sleepSpan);

36.}

37.catch(Exceptione){

38.e.printStackTrace();

39.}

40.}

41.}

42.}

view plaincopy to clipboardprint?

1.packagecom.ball;

2.

3.importandroid.graphics.Bitmap;

4.importandroid.graphics.Canvas;

5.

6.publicclass Movable {

7.intstartX;

8.intstartY;

9.int x = 0;

10.int y = 60;

11.int vt = 20;

12.int r;

13.doubletimeX;

14.Bitmapbitmap = null;

15.BallThreadbt = null;

16.

17.publicMovable(int x, int y, int r, Bitmap bitmap) {

18.this.startX= x;

19.this.x =x;

20.this.startY= y;

21.this.y =y;

22.this.r =r;

23.this.bitmap= bitmap;

24.timeX =System.nanoTime();

25.bt = newBallThread(this);

26.bt.start();

27.}

28.

29.publicvoid drawSelf(Canvas canvas) {

30.canvas.drawBitmap(this.bitmap,x, y, null);

31.}

32.}

view plaincopy to clipboardprint?

1.packagecom.ball;

2.

3.

4.

5.publicclass BallThread extends Thread {

6.Movablefather;

7.booleanflag = false;

8.intsleepSpan = 100;

9.booleandirector = true;

10.intlengthSpan = 10;

11.

12.publicBallThread(Movable father){

13.this.father= father;

14.this.flag= true;

15.}

16.

17.publicvoid run() {

18.while(flag){

19.if(father.x> 270) {

20.director= false;

21.}

22.if(father.x<= 0) {

23.director= true;

24.}

25.if(director== true) {

26.father.x= father.x + lengthSpan;

27.} else {

28.father.x= father.x - lengthSpan;

29.}

30.

31.try{

32.Thread.sleep(sleepSpan);

33.}

34.catch(Exceptione){

35.e.printStackTrace();

36.}

37.}

38.}

39.}

· 上一篇:2. android 边框圆角

· 下一篇:3.android opengl glViewport()

1. android 背景渐变色(shape,gradient)

设置背景色可以通过在res/drawable里定义一个xml,如下:

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<shape xmlns:android="http://schemas.android.com/apk/res/android">

3.<gradient

4.android:startColor="#FFF"

5.android:endColor="#000"

6.android:angle="45"

7./>

8.</shape>

shape是用来定义形状的,gradient定义该形状里面为渐变色填充,startColor起始颜色,endColor结束颜色,angle表示方向角度。当angle=0时,渐变色是从左向右。 然后逆时针方向转,当angle=90时为从下往上。

实现过程:

第一步:

res/drawable/background_login.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<shape xmlns:android="http://schemas.android.com/apk/res/android">

3.<gradient

4.android:startColor="#FFF"

5.android:endColor="#000"

6.android:angle="45"

7./>

8.</shape>

第二步:

res/layout/login.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout

3.xmlns:android="http://schemas.android.com/apk/res/android"

4.android:orientation="vertical"

5.android:layout_width="fill_parent"

6.android:layout_height="fill_parent"

7.android:background="@drawable/background_login">

8.

9.</LinearLayout>

第三步:

view plaincopy to clipboardprint?

1.importandroid.app.Activity;

2.importandroid.os.Bundle;

3.

4.publicclass LoginActivity extends Activity {

5.@Override

6.publicvoid onCreate(Bundle savedInstanceState) {

7.super.onCreate(savedInstanceState);

8.setContentView(R.layout.login);

9.}

10.}

效果图:

分享到:

· 上一篇:27. BroadcastReceiver 消息广播详解----简单监控拨打电话

· 下一篇:28. android——miniTwitter登录界面 详解

2. android 边框圆角

设置边框圆角可以在drawable目录里定义一个xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<shape xmlns:android="http://schemas.android.com/apk/res/android">

3.<solid android:color="#000000"/>

4.<corners android:topLeftRadius="10dp"

5.android:topRightRadius="10dp"

6.android:bottomRightRadius="10dp"

7.android:bottomLeftRadius="10dp"/>

8.</shape>

解释: solid的表示填充颜色,为了简单,这里用的是黑色。

而corners则是表示圆角,注意的是这里bottomRightRadius是左下角而不是右下角,bottomLeftRadius右下角。

当然上面的效果也可以像下面一样设置,如下:

view plaincopy to clipboardprint?

1.<cornersandroid:radius="5dp" />

如果想引用这个xml,只需要@drawable/corners_bg.xml即可

view plaincopy to clipboardprint?

1.android:background="@drawable/corners_bg"

具体步骤如下:

第一步:

在drawable里面定义一个名为corners_bg.xml

/CornerDemo/res/drawable-mdpi/corners_bg.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<shape xmlns:android="http://schemas.android.com/apk/res/android">

3.<solid android:color="#000000"/>

4.<corners android:topLeftRadius="10dp"

5.android:topRightRadius="10dp"

6.android:bottomRightRadius="10dp"

7.android:bottomLeftRadius="10dp"/>

8.</shape>

第二步:

/CornerDemo/res/layout/main.xml

view plaincopy to clipboardprint?

1.<?xml version="1.0"encoding="utf-8"?>

2.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

3.android:orientation="vertical"

4.android:layout_width="fill_parent"

5.android:layout_height="fill_parent"

6.android:background="#FFFFFF"

7.>

8.<RelativeLayout

9.android:id="@+id/login_div"

10.android:layout_width="fill_parent"

11.android:layout_height="150dip"

12.android:padding="15dip"

13.android:layout_margin="15dip"

14.android:background="@drawable/corners_bg"

15.>

16.</RelativeLayout>

17.

18.</LinearLayout>

效果图如下:

分享到:

· 上一篇:28. android——miniTwitter登录界面 详解

· 下一篇:1、android 模拟小球来回撞墙效果(游戏的开始)

4. android 设置全屏且无标题

requestWindowFeature(Window.FEATURE_NO_TITLE); //无标题
getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

java.nio.ByteBuffer 详解

Buffer 类

定义了一个可以线性存放primitive type数据的容器接口。Buffer主要包含了与类型(byte, char…)无关的功能。
值得注意的是Buffer及其子类都不是线程安全的。

每个Buffer都有以下的属性:

capacity
这个Buffer最多能放多少数据。capacity一般在buffer被创建的时候指定。

limit
在Buffer上进行的读写操作都不能越过这个下标。当写数据到buffer中时,limit一般和capacity相等,当读数据时,
limit代表buffer中有效数据的长度。

position
读/写操作的当前下标。当使用buffer的相对位置进行读/写操作时,读/写会从这个下标进行,并在操作完成后,
buffer会更新下标的值。

mark
一个临时存放的位置下标。调用mark()会将mark设为当前的position的值,以后调用reset()会将position属性设
置为mark的值。mark的值总是小于等于position的值,如果将position的值设的比mark小,当前的mark值会被抛弃掉。

这些属性总是满足以下条件:
0 <= mark <= position <= limit <= capacity

limit和position的值除了通过limit()和position()函数来设置,也可以通过下面这些函数来改变:

Buffer clear()
把position设为0,把limit设为capacity,一般在把数据写入Buffer前调用。

Buffer flip()
把limit设为当前position,把position设为0,一般在从Buffer读出数据前调用。

Buffer rewind()
把position设为0,limit不变,一般在把数据重写入Buffer前调用。

Buffer对象有可能是只读的,这时,任何对该对象的写操作都会触发一个ReadOnlyBufferException。
isReadOnly()方法可以用来判断一个Buffer是否只读。


ByteBuffer 类

在Buffer的子类中,ByteBuffer是一个地位较为特殊的类,因为在java.io.channels中定义的各种channel的IO
操作基本上都是围绕ByteBuffer展开的。

ByteBuffer定义了4个static方法来做创建工作:

ByteBuffer allocate(intcapacity) //创建一个指定capacity的ByteBuffer。
ByteBuffer allocateDirect(int capacity) //创建一个direct的ByteBuffer,这样的ByteBuffer在参与IO操作时性能会更好
ByteBuffer wrap(byte [] array)
ByteBuffer wrap(byte [] array, int offset, int length) //把一个byte数组或byte数组的一部分包装成ByteBuffer。

ByteBuffer定义了一系列get和put操作来从中读写byte数据,如下面几个:
byte get()
ByteBuffer get(byte [] dst)
byte get(int index)
ByteBuffer put(byte b)
ByteBuffer put(byte [] src)
ByteBuffer put(int index, byte b)
这些操作可分为绝对定位和相对定为两种,相对定位的读写操作依靠position来定位Buffer中的位置,并在操
作完成后会更新position的值。在其它类型的buffer中,也定义了相同的函数来读写数据,唯一不同的就是一
些参数和返回值的类型。

除了读写byte类型数据的函数,ByteBuffer的一个特别之处是它还定义了读写其它primitive数据的方法,如:

int getInt() //从ByteBuffer中读出一个int值。
ByteBuffer putInt(int value) // 写入一个int值到ByteBuffer中。

读写其它类型的数据牵涉到字节序问题,ByteBuffer会按其字节序(大字节序或小字节序)写入或读出一个其它
类型的数据(int,long…)。字节序可以用order方法来取得和设置:
ByteOrder order() //返回ByteBuffer的字节序。
ByteBuffer order(ByteOrder bo) // 设置ByteBuffer的字节序。

ByteBuffer另一个特别的地方是可以在它的基础上得到其它类型的buffer。如:
CharBuffer asCharBuffer()
为当前的ByteBuffer创建一个CharBuffer的视图。在该视图buffer中的读写操作会按照ByteBuffer的字节
序作用到ByteBuffer中的数据上。

用这类方法创建出来的buffer会从ByteBuffer的position位置开始到limit位置结束,可以看作是这段数据
的视图。视图buffer的readOnly属性和direct属性与ByteBuffer的一致,而且也只有通过这种方法,才可
以得到其他数据类型的direct buffer。

ByteOrder
用来表示ByteBuffer字节序的类,可将其看成java中的enum类型。主要定义了下面几个static方法和属性:
ByteOrder BIG_ENDIAN 代表大字节序的ByteOrder。
ByteOrder LITTLE_ENDIAN 代表小字节序的ByteOrder。
ByteOrder nativeOrder() 返回当前硬件平台的字节序。

MappedByteBuffer
ByteBuffer的子类,是文件内容在内存中的映射。这个类的实例需要通过FileChannel的map()方法来创建。

接下来看看一个使用ByteBuffer的例子,这个例子从标准输入不停地读入字符,当读满一行后,将收集的字符
写到标准输出:

public static void main(String[] args)
throws IOException
{
// 创建一个capacity为256的ByteBuffer
ByteBuffer buf = ByteBuffer.allocate(256);
while (true) {
// 从标准输入流读入一个字符
int c = System.in.read();
// 当读到输入流结束时,退出循环
if (c == -1)
break;
// 把读入的字符写入ByteBuffer中
buf.put((byte) c);
// 当读完一行时,输出收集的字符
if (c == '\n') {
// 调用flip()使limit变为当前的position的值,position变为0,
// 为接下来从ByteBuffer读取做准备
buf.flip();
// 构建一个byte数组
byte [] content = new byte[buf.limit()];
// 从ByteBuffer中读取数据到byte数组中
buf.get(content);
// 把byte数组的内容写到标准输出
System.out.print(new String(content));
// 调用clear()使position变为0,limit变为capacity的值,
// 为接下来写入数据到ByteBuffer中做准备
buf.clear();
}
}
}

你可能感兴趣的:(android)