我是Android开发的新手,我想用TextView中的文件替换TextView中的文件并将其显示在textView1中。我搜索了很多问题,但解决方案对我不起作用。感谢帮助。这是我的代码:
fragment_profile中的文本视图:
<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;
}
}
}
答案 0 :(得分:0)
我还没有测试过您的代码,但我要检查的第一件事是访问ExternalStorage 。也许您必须在应用清单中添加<uses-permission>
条目以允许访问外部存储(android.permission.READ_EXTERNAL_STORAGE)。
答案 1 :(得分:0)
使用此代码可以正常工作:
File logFile = new File("sdcard/text.txt");
if (logFile.exists())
{
try
{ FileInputStream fIn = new FileInputStream(logFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";}
text.setText(aBuffer);
myReader.close();
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
并确保使用清单上的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>