根据客户的需求,今天安卓应用中要加一个功能,打开指定目录,并展示其中的文件列表,选中其中一个,就打开,目录如下:

Android 读取目录中的文件列表并展示_Android教程


这个需求比较笼统,并且包含的细节也比较多,因此分布实现:


一. 布局文件

   ScrollView滚动列表:dialog_spec_item.xml

<ScrollView 
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:scrollbars="vertical"
	android:fadingEdge="vertical"
	android:background="#EDEDED">
      
    	<LinearLayout
    		android:layout_width="fill_parent"
    		android:layout_height="fill_parent"
    		android:orientation="vertical"
    		android:scrollbars="vertical">
            
    		<ListView 
        		android:id="@+id/spec_item_list" 
        		android:layout_width="fill_parent" 
        		android:layout_height="fill_parent"
        		android:dividerHeight="1px"
        		android:divider="#B8B8B8" > 
    		</ListView> 
    	
    	</LinearLayout>
    
 </ScrollView>
     

列表项布局:spec_item_list.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="horizontal" >     
    
	    <TextView 
    	android:id="@+id/spec_item_seq"
    	android:layout_width="0dp"
    	android:layout_weight="1"
    	android:layout_height="wrap_content"
    	style="@style/SampleQueryListText"
    	android:gravity="center"
    	android:padding="4dp"/> 
    
	    <View 
        android:layout_width="0.5px" 
        android:layout_height="fill_parent" 
        android:background="#B8B8B8" 
        android:visibility="visible"/>    
    
	    <TextView 
    	android:id="@+id/spec_item_name"
    	android:layout_width="0dp"
    	android:layout_weight="9"
    	android:layout_height="wrap_content"
    	style="@style/SampleQueryListText"
    	android:padding="4dp"/>   
    
</LinearLayout>


  初始化布局文件:

private AlertDialog dlgSpecItem;	
private View specItemView;

//项目操作说明书对话框
specItemView = factory.inflate(R.layout.dialog_spec_item, null);
lv = (ListView) specItemView.findViewById(R.id.spec_item_list);

二. 读取目录中的文件列表

//打开指定目录,显示项目说明书列表,供用户选择
PATH = Environment.getExternalStorageDirectory() + "/";
      		
File specItemDir = new File(PATH + DT.APP_FOLDER + "/SPEC_ITEM");
if(!specItemDir.exists()){
	specItemDir.mkdir();
}
	        			
if(!specItemDir.exists()){
	AppUtil.alert(UI.operation_specification_folder_not_found, getActivity());
}else{
//取出文件列表:
final File[] files = specItemDir.listFiles();


三. 数据填充到布局中

List<HashMap<String, Object>> specs = new ArrayList<HashMap<String,Object>>();
int seq = 0;
for(File spec : files){   
	seq++;
	HashMap<String, Object> hashMap = new HashMap<String, Object>();  
	hashMap.put("seq", seq);
	hashMap.put("name", spec.getName());  
	specs.add(hashMap);  
}   
	        	
SimpleAdapter adapter =
	new SimpleAdapter(
	    getActivity(),
	    specs,
	    R.layout.list_item_spec,
	    new String[]{"seq","name"},
	    new int[]{R.id.spec_item_seq, R.id.spec_item_name}
	);  
	        	
lv.setAdapter(adapter);
AppUtil.setListViewHeightBasedOnChildren(lv);//自定义,调整布局,防止只显示第一条数据的问题
				
lv.setOnItemClickListener(new OnItemClickListener() {
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1,int position, long aid) {
		String filePath = files[position].getAbsolutePath();
		Intent intent = getWordFileIntent(filePath); 
		startActivity(intent);
	}
});


四. 打开窗口

//获得自定义对话框
if(dlgSpecItem != null){
	dlgSpecItem.setView(null);
}
if(specItemView.getParent() != null){
	((FrameLayout)specItemView.getParent()).removeView(specItemView);
}

dlgSpecItem = new AlertDialog.Builder(getActivity())
.setView(specItemView)
.setNegativeButton(UI.close, null)
.show();
				
dlgSpecItem.setCanceledOnTouchOutside(false);

文件列表效果:

Android 读取目录中的文件列表并展示_Android开发_02


打开一个其中一个文件:

Android 读取目录中的文件列表并展示_Android教程_03


其他,引用的方法:

/**
 * 获取打开word文件的intent     
*/
public static Intent getWordFileIntent( String param ){    
      Intent intent = new Intent("android.intent.action.VIEW");     
      intent.addCategory("android.intent.category.DEFAULT");     
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);     
      Uri uri = Uri.fromFile(new File(param ));     
      intent.setDataAndType(uri, "application/msword");     
      return intent;     
}     

/**
 * 解决ListView在ScrollView中只能显示一行数据的问题
 * @param listView
*/
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}