簡體   English   中英

選擇一個文本文件,然后在 Android 平台上閱讀它

[英]Choose a text file and then read it on Android Platform

我的 android 應用程序有一個 Button 小部件,其中除了其他必要的文本之外,我還在文件activity_main.xml編寫了以下內容。

<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Numbers"
   android:id="@+id/btnBrowse"
   android:onClick="clickButtonBrowse"
 />

在文件MainActivity.java除了其他函數之外,我寫了以下內容:

protected void clickButtonBrowse() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/plain");
    startActivity(intent, FILE_REQUEST_CODE);
}

我的想法是打開一個文件瀏覽器,然后選擇一個文件。 我從這個問題中獲得了關於選擇文件的幫助。

現在我不知道以下幾點:

  1. 如何從意圖中獲取文件的名稱,以便我可以閱讀它。
  2. 這個FILE_REQUEST_CODE是如何定義的? 允許的值是多少?

你能幫我嗎?

您需要 startActivityForResult 而不是 startActivity,就像您使用的示例一樣。
然后你可以:

public synchronized void onActivityResult(final int requestCode,
        int resultCode, final Intent data) {

    if (resultCode == Activity.RESULT_OK) {
        String filePath = data.getStringExtra(FileDialog.RESULT_PATH);
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM