我是Android开发的新手,我想用TextView中的文本替换TextView中的文件并将其显示在textView1中。我搜索了很多问题,但解决方案并不适合我。感谢帮助。这里是我的代码:在fragment_profile如何从SD卡读取文件并显示文本?
文本视图:
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="@string/nick"
android:textColor="#FFFFFF" />
而这正是活动:
package com.tom411.pyzdit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ProfileActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
TextView tv = (TextView) findViewById(R.id.textView1);
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir,"/PyzdIt/name.txt");
if(file.exists())
{
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.read();
br.close();
}
catch (IOException e) {
}
tv.setText(text);
}
}
public void Back(View view)
{
Intent intent = new Intent(ProfileActivity.this, MainActivity.class);
startActivity(intent);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profile,
container, false);
return rootView;
}
}
}
许可可能是这将帮助:http://stackoverflow.com/questions/5453708/android-how-to-use-environment-getexternalstoragedirectory – Nabin