[Android] reads and displays all the images on the sdcard. The reading progress bar is displayed,
Although the app below has not yet achieved the level of fast graph browsing and ES file browsers, there will still be problems such as reading too long and memory overflow in the case of large sdcard, but the basic idea is as follows.
For example, there are four images on the sdcard,
Open the app and read all the images on the SD card. The reading progress bar is displayed.
The production process is as follows:
1. First, set the characters in res \ values \ strings. xml as follows.
<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "app_name"> Read all images under sdcard </string> <string name = "action_settings"> Settings </string> <string name = "imageView_description "> big chart </string> </resources>
2. Modify res \ layout \ activity_main.xml to form a layout. Here, the layout is replaced with the [Android] Gallery-style image browser with HorizontalScrollView, the parameter transfer of OnClickListener (click to open the link) is exactly the same, but here, the LinearLayout under HorizontalScrollView is generated using Java code, so the HorizontalScrollView is assigned an id.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="200dp" android:contentDescription="@string/imageView_description" android:paddingTop="10dp" /> <HorizontalScrollView android:id="@+id/horizontalScrollView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:scrollbars="horizontal" > </HorizontalScrollView></LinearLayout>
3. Then, in the same way as reading images from sdcard in [Android] (click to open the link. xml insertion <uses-permission android: name = "android. permission. READ_EXTERNAL_STORAGE "/> and <uses-permission android: name =" android. permission. WRITE_EXTERNAL_STORAGE "/> requires read and write permissions on sdcard. The file is modified as follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "com. example. asyncread "android: versionCode =" 1 "android: versionName =" 1.0 "> <uses-sdk android: minSdkVersion =" 8 "android: targetSdkVersion = "18"/> <uses-permission android: name = "android. permission. READ_EXTERNAL_STORAGE "/> <! -- Permission to read data from SDCard --> <uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/> <! -- Required to write data to SDCard --> <application android: allowBackup = "true" android: icon = "@ drawable/ic_launcher" android: label = "@ string/app_name" android: theme = "@ style/AppTheme"> <activity android: name = "com. example. asyncread. 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>
4. Finally, it is the key of the entire program. It is the compilation of MainActivity. java. Here, we first inserted two tool classes, one of which is described in "[Java] Reading the path of all the folders and files under it" (click to open the link) to traverse the files on the sdcard. Of course, remove the Android system folder from the sdcard during traversal. If this folder is not excluded, the system icons will be traversed. It is followed by an image scaling class. If you do not scale the read image, the error of memory overflow will occur when the app is running.
At the beginning of the program, a progress bar is generated in the app header in the onCreate method, and then an asynchronous AsyncTask class is called to read the sdcard files, which is similar to the image browser in the [Android] Gallery, use HorizontalScrollView to replace Gallery. Use the same method in parameter transfer of OnClickListener (click to open the link) to load image resources one by one. It only applies to the image resources of the app and the image read from the sdcard.
Package com. example. asyncread; import java. io. file; import java. util. arrayList; import android. OS. asyncTask; import android. OS. bundle; import android. OS. environment; import android. view. gravity; import android. view. view; import android. view. view. onClickListener; import android. view. viewGroup; import android. view. window; import android. widget. horizontalScrollView; import android. widget. imageView; import android. Widget. linearLayout; import android. widget. linearLayout. layoutParams; import android. widget. textView; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; public class MainActivity extends Activity {// Android component private HorizontalScrollView horizontalScrollView1; private ImageView imageView1; // used to store all image paths on the sdcard public static ArrayList <String> dirAllStrArr = new ArrayList <String> (); // class public static void DirAll (File dirFile) throws Exception {if (dirFile. exists () {File files [] = dirFile. listFiles (); for (File file: files) {if (file. isDirectory () {String fileName = file. getName (); // except for the Android folder on sdcard. If (! FileName. endsWith ("Android") {// recursively calls a folder. DirAll (file) ;}} else {// if it is an image file, press it into the array String fileName = file. getName (); if (fileName. endsWith (". jpg ") | fileName. endsWith (". jpeg ") | fileName. endsWith (". bmp ") | fileName. endsWith (". gif ") | fileName. endsWith (". png ") {// if a file is encountered, put it in the array if (dirFile. getPath (). endsWith (File. separator) {dirAllStrArr. add (dirFile. getPath () + file. getName ();} else {dirAllStrArr. add (dirFile. getPath () + File. separator + file. getN Ame () ;}}}}// the image loading class public static BitmapFactory. options getHeapOpts (File file) {BitmapFactory. options opts = new BitmapFactory. options (); // The larger the number, the smaller the heap occupied by the image to be read. Otherwise, if (file. length () <20480) {// 0-20kopts.inSampleSize = 1; // here it indicates the scaled size} else if (file. length () <51200) {// 20-50kopts.inSampleSize = 2;} else if (file. length () <307200) {// 50-300kopts.inSampleSize = 4;} else if (file. length () <819200) {// 300-800kopts.inSampleSize = 6;} else if (file. length () <1048576) {// 800-1024kopts.inSampleSize = 8;} else {opts. inSampleSize = 10;} return opts;} class MyTask extends AsyncTask <Void, Integer, LinearLayout> {@ Override // What do you do before the task starts protected void onPreExecute () {setProgressBarVisibility (true); // displays the progress bar super. onPreExecute () ;}@ Overrideprotected LinearLayout doInBackground (Void... arg0 ){// Generate a horizontal linear layout LinearLayout linearLayout1 = new LinearLayout (MainActivity. this); LayoutParams layoutParams = new LayoutParams (ViewGroup. layoutParams. WRAP_CONTENT, ViewGroup. layoutParams. WRAP_CONTENT); linearLayout1.setOrientation (LinearLayout. HORIZONTAL); linearLayout1.setLayoutParams (layoutParams); // apply to the new linear layout/* traverse all sdcard folders to start */String sdpath = Environment. getExternalStorageDirectory (). getAbsoluteP Ath (); // get the root path of sdcard File dirFile = new File (sdpath); try {DirAll (dirFile);} catch (Exception e) {e. printStackTrace ();}/* traverses all the folders under sdcard and ends * // obtains all the image paths under sdcard, and then traverses the array for (int I = 0; I <dirAllStrArr. size (); I ++) {String filePath = dirAllStrArr. get (I); File file = new File (filePath); Bitmap bm = BitmapFactory. decodeFile (filePath, getHeapOpts (file); LinearLayout linearLayout2 = new LinearLayou T (MainActivity. this); // set the parameter for the new linear layout. The width is 100, and the height is the matching parent component. That is, the height of the horizontal scrolling view is LayoutParams layoutParams1 = new LayoutParams (100, ViewGroup. layoutParams. MATCH_PARENT); layoutParams1.gravity = Gravity. CENTER_HORIZONTAL; // sets the horizontal center of components in the linear layout linearLayout2.setOrientation (LinearLayout. VERTICAL); // set the new linear layout android: orientation = "vertical" linearLayout2.setLayoutParams (layoutParams1); // apply it to the new linear layout ImageView imageView2 = new ImageView (MainActivity. this); imageView2.setId (I + 20000); // here, because id cannot be a character, all the image IDs are set to 20002 ,... to facilitate the following image, click the image view2.setimagebitmap (bm) controlled by the listener; // place the I image in the array to the image view imageView2.setAdjustViewBounds (true ); // auto scale to imageView2.setMaxHeight (80); // The Image Height Is 80dpimageView2. setPadding (10, 10, 10, 10); imageView2.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View view) {String FilePath = dirAllStrArr. get (view. getId ()-20000); File file = new File (filePath); Bitmap bm = BitmapFactory. decodeFile (filePath, getHeapOpts (file); imageView1.setImageBitmap (bm); // after removing the clicked image id, minus 20000 is the position of the image to be displayed in the Image array .}}); // Load the Image view to the new linear layout of linearLayout2.addView (imageView2); // generate a new label text TextView textView = new TextView (MainActivity. this); textView. setText (filePath); textView. setTextSize (15); // The label text is centered horizontally in textView. setGravity (Gravity. CENTER); // Add to the new linear layout after linearLayout2.addView (textView); linearLayout1.addView (linearLayout2); publishProgress (I); // call onProgressUpdate method} return linearLayout1 ;} @ Overrideprotected void onProgressUpdate (Integer... values) {setProgress (values [0] * 2500); // update progress bar super. onProgressUpdate (values);} // @ Overrideprotected void onPostExecute (LinearLayout result) {setProgressBarVisibility (false); merge (result); // put doInBackground () the final horizontal linear layout is placed in the Horizontal Rolling layout super. onPostExecute (result) ;}@overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_PROGRESS); // generate a progress bar in the header, which must be in setContentView (R. layout. activity_main); setContentView (R. layout. activity_main); // obtain the horizontalScrollView1 = (HorizontalScrollView) findViewById (R. id. horizontalScrollView1); imageView1 = (ImageView) findViewById (R. id. imageView1); new mytask(cmd.exe cute (); // start MyTask task }}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.