目錄html
第31章ListView
ListView是一個能夠顯示滾動的列表項的一個視圖,列表項可能來自於一個列表適配器或一個數組適配器。選取ListView中的一項,將會觸發一個事件,咱們能夠編寫該事件的監聽器。
31.1 概覽
1.ListView之因此難以使用,是由於你必須獲取一個ListAdapter形式的數據源。ListAdapter還爲ListView上的每一項提供了佈局,所以,ListAdapter實際上在ListView的生命中扮演一個很是重要的角色。
31.2 建立一個ListAdapter
1.ListAdapter的具體實現之一是ArrayAdapter類。ArrayAdapter類是由對象的一個數組來支持的。每個對象的toString方法所返回的字符串,用於填充ListView中的每一項。
2.ArrayAdapter類提供了幾個構造方法,全部構造方法都須要傳入一個Context以及一個資源標識符,後者指向一個包含TextView的佈局。這是由於ListView中的每一項都是一個TextView。
31.3 使用一個ListView
1.代碼清單31.1 ListViewDemo1的res/values/strings.xml文件java
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">ListViewDemo1</string> <string name="action_settings">Settings</string> <string-array name="players"> <item>Player 1</item> <item>Player 2</item> <item>Player 3</item> <item>Player 4</item> <item>Player 5</item> </string-array> </resources>
2.代碼清單31.2 list_item.xml文件android
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/list_item" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="7dip" android:textSize="16sp" android:textColor="@android:color/holo_green_dark" android:textStyle="bold" > </TextView>
3.代碼清單31.3 ListViewDemo1的activity_main.xml文件git
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/listView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
3.代碼清單31.4 ListViewDemo1的MainActivity類數組
package com.example.listviewdemo1; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String[] values = getResources().getStringArray( R.array.players); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, R.layout.list_item, values); ListView listView = (ListView) findViewById(R.id.listView1); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { String item = (String) parent.getItemAtPosition(position); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("Selected item: " + item).setTitle("ListView"); builder.create().show(); Log.d("ListView", "Selected item : " + item); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
31.4 擴展ListActivity並編寫一個定製的適配器
1.代碼清單31.5 pretty_adapter.xml文件android-studio
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/icon" android:layout_width="36dp" android:layout_height="fill_parent"/> <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_vertical" android:padding="12dp" android:textSize="18sp" android:textColor="@android:color/holo_blue_bright"/> </LinearLayout>
2.代碼清單31.6 PrettyAdapter類app
package com.example.listviewdemo2; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class PrettyAdapter extends ArrayAdapter<String> { private LayoutInflater inflater; private String[] items; private Drawable icon; private int viewResourceId; public PrettyAdapter(Context context, int viewResourceId, String[] items, Drawable icon) { super(context, viewResourceId, items); inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.items = items; this.icon = icon; this.viewResourceId = viewResourceId; } @Override public int getCount() { return items.length; } @Override public String getItem(int position) { return items[position]; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = inflater.inflate(viewResourceId, null); ImageView imageView = (ImageView) convertView.findViewById(R.id.icon); imageView.setImageDrawable(icon); TextView textView = (TextView) convertView.findViewById(R.id.label); textView.setText(items[position]); return convertView; } }
3.代碼清單31.7 ListViewDemo2的MainActivity框架
package com.example.listviewdemo2; import android.app.ListActivity; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; public class MainActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Since we're extending ListActivity, we do // not need to call setContentView(); Context context = getApplicationContext(); Resources resources = context.getResources(); String[] items = resources.getStringArray( R.array.players); Drawable drawable = resources.getDrawable( R.drawable.pretty); setListAdapter(new PrettyAdapter(context, R.layout.pretty_adapter, items, drawable)); } @Override public void onListItemClick(ListView listView, View view, int position, long id) { Log.d("listView2", "listView:" + listView + ", view:" + view.getClass() + ", position:" + position ); } }
31.5 樣式化選取的項
爲了讓選取的項看上去和剩下的其餘的項有所區別,能夠將ListView的選擇模式設置爲CHOICE_MODE_SINGLE。
1.代碼清單31.8 主活動的佈局文件(activity_main.xml)ide
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ListView android:id="@+id/listView1" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent"/> <ListView android:id="@+id/listView2" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent"/> </LinearLayout>
2.代碼清單31.9 MainActivity類佈局
package com.example.listviewdemo3; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String[] cities = {"Rome", "Venice", "Basel"}; ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, cities); ListView listView1 = (ListView) findViewById(R.id.listView1); listView1.setAdapter(adapter1); listView1.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.list_item, cities); ListView listView2 = (ListView) findViewById(R.id.listView2); listView2.setAdapter(adapter2); listView2.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } }
3.代碼清單31.10 list_item.xml文件
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/list_item" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="7dip" android:textSize="16sp" android:textStyle="bold" android:background="@drawable/list_selector" />
4.代碼清單31.11 drawable/list_selector.xml文件
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_activated="true" android:drawable="@drawable/activated"/> </selector>
5.代碼清單31.12 drawable/activated.xml文件
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <corners android:radius="10dp"/> <gradient android:startColor="#FF00FF00" android:endColor="#FFFF00" android:angle="45"/> </shape>
第32章 GridView
GridView是可以在一個表格中顯示可滾動的項的一個列表的視圖。它和ListView類似,只不過它在多個列中顯示項目,而不像ListView那樣,只是在單個的列中顯示項。和ListView同樣,GridView也經過一個ListAdapter獲取數據源和佈局。
32.2 使用GridView
1.代碼清單32.1 AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.gridviewdemo1" android:versionCode="1" android:versionName="1.0" > <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.gridviewdemo1.MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
2.代碼清單32.2 GridViewAdapter類
package com.example.gridviewdemo1; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class GridViewAdapter extends BaseAdapter { private Context context; public GridViewAdapter(Context context) { this.context = context; } private int[] icons = { android.R.drawable.btn_star_big_off, android.R.drawable.btn_star_big_on, android.R.drawable.alert_light_frame, android.R.drawable.alert_dark_frame, android.R.drawable.arrow_down_float, android.R.drawable.gallery_thumb, android.R.drawable.ic_dialog_map, android.R.drawable.ic_popup_disk_full, android.R.drawable.star_big_on, android.R.drawable.star_big_off, android.R.drawable.star_big_on }; @Override public int getCount() { return icons.length; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(context); imageView.setLayoutParams(new GridView.LayoutParams(100, 100)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(10, 10, 10, 10); } else { imageView = (ImageView) convertView; } imageView.setImageResource(icons[position]); return imageView; } }
3.代碼清單32.3 activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" />
4.代碼清單32.4 MainActivity類
package com.example.gridviewdemo1; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new GridViewAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
第33章樣式和主題
33.1 概覽
1.要對一個視圖應用樣式,須要使用style屬性。建立一個樣式的優勢在於,可以讓樣式變得可複用和可共享。樣式支持繼承,所以,能夠擴展一個樣式以建立一個新的樣式。
2.注意style屬性,和其餘的屬性不一樣,它沒有使用android前綴。所以,其形式爲style而不是android:style。使用系統樣式,須要在style屬性的值前加上android的前綴。
33.2 使用樣式
1.代碼清單33.1 styles.xml文件
<resources xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. --> <style name="AppBaseTheme" parent="android:Theme.Light"> <!-- Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. --> </style> <!-- Application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> </style> <style name="WhiteOnRed"> <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> <item name="android:textColor">#FFFFFF</item> <item name="android:background"> @android:color/holo_red_light </item> <item name="android:typeface">serif</item> <item name="android:textStyle">bold</item> <item name="android:textSize">25sp</item> <item name="android:padding">30dp</item> </style> <style name="WhiteOnRed.Italic"> <item name="android:textStyle">bold|italic</item> </style> <style name="WhiteOnGreen" parent="WhiteOnRed"> <item name="android:background"> @android:color/holo_green_light </item> </style> </resources>
2.代碼清單33.2 activity_main.xml佈局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" style="@style/WhiteOnRed" android:text="Style WhiteOnRed" /> <TextView android:id="@+id/textView2" android:layout_below="@id/textView1" android:layout_marginLeft="20sp" android:layout_marginTop="10sp" style="@style/WhiteOnRed.Italic" android:text="Style WhiteOnRed.Italic" /> <TextView android:id="@+id/textView3" android:layout_below="@id/textView2" android:layout_toEndOf="@id/textView2" style="@style/WhiteOnGreen" android:text="Style WhiteOnGreen" /> <TextView android:id="@+id/textView4" android:text="Style TextAppearance.Holo.Medium.Inverse" android:layout_below="@id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@android:style/TextAppearance.Holo.Medium"/> </RelativeLayout>
3.代碼清單33.3 MainActivity類
package com.example.styledemo1; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
第34章位圖處理
34.1 概覽
1.位圖(bitmap)是一種圖像文件格式,它能夠獨立於顯示設備來存儲數字圖像。位圖的簡單的含義就是位的地圖。現在,這個術語還包括支持有損壓縮和無損壓縮的其餘格式,包括JPEG、GIF和PNG格式。GIF和PNG格式支持透明度和無損壓縮,而JPEG格式支持有損壓縮,而且不支持透明度。表示數字圖像的另外一種方式是使用數學表達式。這樣的圖像叫做矢量圖。
2.使用一個BitmapFactory.Options能夠作兩件事情。第一件事情是,容許你將最終的位圖配置爲一個類,從而能夠對位圖縮小取樣(down-sample),將位圖設置爲可變,而且配置其精度。第二件事情是,可使用BitmapFactory.Options來讀取一幅位圖的屬性而不須要真正加載它。若是認爲這個尺寸太大了,那麼能夠對其縮小取樣,以節省內存。
3.若是給BitmapFactory.Options的inSampleSize字段告訴系統如何對一個位圖採樣。大於1的值表示圖像應該縮小採樣。
34.2 位圖處理
1.代碼清單34.1 AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.bitmapdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.bitmapdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
2.代碼清單34.2 activity_main.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="bottom" tools:context=".MainActivity" > <ImageView android:id="@+id/image_view1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/text_content_desc"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/text_sample_size"/> <TextView android:id="@+id/sample_size" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:onClick="scaleUp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/action_scale_up" /> <Button android:onClick="scaleDown" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/action_scale_down" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:onClick="changeImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/action_change_image" /> <TextView android:id="@+id/image_info" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> </LinearLayout>
3.代碼清單34.3 MainActivity類
package com.example.bitmapdemo; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends Activity { int sampleSize = 2; int imageId = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); refreshImage(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } public void scaleDown(View view) { if (sampleSize < 8) { sampleSize++; refreshImage(); } } public void scaleUp(View view) { if (sampleSize > 2) { sampleSize--; refreshImage(); } } private void refreshImage() { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.drawable.image1, options); int imageHeight = options.outHeight; int imageWidth = options.outWidth; String imageType = options.outMimeType; StringBuilder imageInfo = new StringBuilder(); int id = R.drawable.image1; if (imageId == 2) { id = R.drawable.image2; imageInfo.append("Image 2."); } else if (imageId == 3) { id = R.drawable.image3; imageInfo.append("Image 3."); } else if (imageId == 4) { id = R.drawable.image4; imageInfo.append("Image 4."); } else { imageInfo.append("Image 1."); } imageInfo.append(" Original Dimension: " + imageWidth + " x " + imageHeight); imageInfo.append(". MIME type: " + imageType); options.inSampleSize = sampleSize; options.inJustDecodeBounds = false; Bitmap bitmap1 = BitmapFactory.decodeResource( getResources(), id, options); ImageView imageView1 = (ImageView) findViewById(R.id.image_view1); imageView1.setImageBitmap(bitmap1); TextView sampleSizeText = (TextView) findViewById(R.id.sample_size); sampleSizeText.setText("" + sampleSize); TextView infoText = (TextView) findViewById(R.id.image_info); infoText.setText(imageInfo.toString()); } public void changeImage(View view) { if (imageId < 4) { imageId++; } else { imageId = 1; } refreshImage(); } }
1.Android中全部的意圖均可以用來啓動活動.
A .True
B .False
正確答案:B 個人答案: A
錯誤緣由:並非全部的意圖均可以用來啓動活動。要確保一個 Intent 可以啓動一個活動,須要在將其傳遞給startActivity 以前,調用其 resolveActivity 方法:
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
不能解析爲一個動做的意圖,若是傳遞給了 startActivity,將會拋出一個異常。
6.調試一個應用程序的最簡單的方法,是使用日誌消息。Android 框架提供了 android.util.Log 類用於記錄日誌消息。Log 類帶日誌級別最高的是()
A .d(debug)
B .i(info)
C .v(verbose)
D .w(warning)
E .e(error)
F .wtf(what a terrible failure)
正確答案: F 個人答案: E
錯誤緣由:
Verbose,Info,Warn,Error和Assert五類Log的重要程度排序以下。
Assert > Error > Warn > Info > Verbose
Log.v():用來記錄Verbose類型日誌
Log.d():用來記錄Debug類型日誌
Log.i():用來記錄Info類型日誌
Log.w():用來記錄Warn類型日誌
Log.e():用來記錄Error類型日誌
Log.wtf():用來記錄Assert類型日誌
24.A main method can only access static or local variables(main方法只能訪問靜態變量或局部變量).
A .true
B .false
正確答案: A 個人答案: B
錯誤緣由:主方法不能訪問非靜態和非局部變量,由於它是靜態方法。特別是,它不能訪問在類級別聲明的任何變量。
https://gitee.com/EvelynYang/eighth_weeks
在新建的AndroidProjects文件夾中運行腳本,第六週及以前都是在IdeaProjects文件夾裏運行。
代碼行數(新增/累積) | 博客量(新增/累積) | 學習時間(新增/累積) | 重要成長 | |
---|---|---|---|---|
目標 | 5000行 | 30篇 | 400小時 | |
第一週 | 200/200 | 2/2 | 20/20 | |
第二週 | 300/500 | 1/3 | 18/38 | |
第三週 | 500/1000 | 1/4 | 38/76 | |
第四周 | 1000/2000 | 1/5 | 20/96 | |
第五週 | 1000/3000 | 1/6 | 25/121 | |
第六週 | 1000/4000 | 1/7 | 25/146 | |
第七週 | 1000/5000 | 1/8 | 25/171 | |
第八週 | 1000/6000 | 1/9 | 15/186 |