main.xml
<activity ... android:screenOrientation="landscape<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ListView android:id="@android:id/list" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@android:id/empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="無檔案" /> </LinearLayout>">...</activity>FileIntentActivity
public class FileIntentActivity extends ListActivity implements OnItemClickListener { private static final String TAG = "FileIntentActivity"; private String parentPath; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.setListAdapter(this.createListAdapter()); ListView lv = (ListView) this.findViewById(android.R.id.list); lv.setOnItemClickListener(this); } private ListAdapter createListAdapter() { List<String> list = new ArrayList<String>(); File sdDir = Environment.getExternalStorageDirectory(); File cwDir = new File(sdDir, "cw1206"); this.parentPath = cwDir.getPath(); Log.d(TAG, "根目錄:" + this.parentPath); File[] files = cwDir.listFiles(); for (File f : files) { if (f.isDirectory()) { continue; } list.add(f.getName()); Log.d(TAG, "加入檔案:" + f.getName()); } return new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { File file = new File(this.parentPath, ((TextView) view).getText().toString()); // 開啟檔案 Intent it = new Intent(Intent.ACTION_VIEW); String ext = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()); Log.d(TAG, "ext: " + ext); if (ext == null || "".equals(ext)) { return; } String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( ext); Log.d(TAG, "mimeType: " + mimeType); // data 與 type 一定要一起呼叫 it.setDataAndType(Uri.fromFile(file), mimeType); // 不可以分開呼叫 // it.setData(Uri.fromFile(file)); // it.setType(mimeType); this.startActivity(it); } }
相關文章
沒有留言:
張貼留言