如何解决使用filepicker选择一个文本文件并将该文本文件的内容加载到Xamarin Android中的“编辑文本”中
在此论坛上在此处提出相关问题后,非常感激能找到打开文件选择器界面的代码,以使用户能够选择MIME类型(“ .txt”)的文件,不,我需要超越此限制,将该文本文件的内容加载到活动布局中显示的编辑文本中... 打开文件选择器界面的代码位于button方法内...为了简而言之,我的其余代码将在下面进行解释。
class Notes:AppCompatActivity
{
//Declare this edit text variable in the class so that all methods can access it without having to redefine it
EditText notes;
protected override void OnCreate(Bundle onSavedInstanceState){
//Assign the edit text
notes = this.FindViewById<EditText>(Resource.Id.editext5);
}
//This button method opens the file picker interface when the button is clicked
private void Button2_Click(object sender,EventArgs e)
{
//Program the open file text behavior from here
Intent intent = new Intent();
intent.SetType("text/plain");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(intent,"Select file"),1);
}
//I had this idea to override StartActivityForResult method but am not even sure that is what i should do
public override void StartActivityForResult(Intent intent,int requestCode)
{
base.StartActivityForResult(intent,requestCode);
}
}
可以帮助我将所选文件中现有文本加载到我的编辑文本中的代码一定会受到赞赏,谢谢...
解决方法
选择文件后,将以OnActivityResult
方法获取数据,您可以尝试以下方法:
class Notes:AppCompatActivity
{
//Declare this edit text variable in the class so that all methods can access it without having to redefine it
EditText notes;
protected override void OnCreate(Bundle onSavedInstanceState){
//Assign the edit text
notes = this.FindViewById<EditText>(Resource.Id.editext5);
}
//This button method opens the file picker interface when the button is clicked
private void Button2_Click(object sender,EventArgs e)
{
//Program the open file text behavior from here
Intent intent = new Intent();
intent.SetType("text/plain");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(intent,"Select file"),1);
}
protected override async void OnActivityResult(int requestCode,[GeneratedEnum] Result resultCode,Intent data)
{
base.OnActivityResult(requestCode,resultCode,data);
if (requestCode == 1 && resultCode == Result.Ok)
{
var uri = data.Data;
var stream = ContentResolver.OpenInputStream(uri);
string str = "";
StringBuffer buf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
while ((str = reader.ReadLine()) != null)
{
buf.Append(str + "\n");
}
stream.Close();
notes.Text = buf.ToString();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。