Android 从原始资源加载文本视图中的文本
我想在第一个活动和第二个活动中单击按钮,将原始资源中的文本加载到文本视图中。我认为这可能是通过Android 从原始资源加载文本视图中的文本,android,android-activity,textview,Android,Android Activity,Textview,我想在第一个活动和第二个活动中单击按钮,将原始资源中的文本加载到文本视图中。我认为这可能是通过putextra,getextra方法实现的。我的文本阅读器到文本视图的代码如下 TextView textView = (TextView)findViewById(R.id.textview_data); String data = readTextFile(this, R.raw.books); textView.setText(data); } public static
putextra
,getextra
方法实现的。我的文本阅读器到文本视图的代码如下
TextView textView = (TextView)findViewById(R.id.textview_data);
String data = readTextFile(this, R.raw.books);
textView.setText(data);
}
public static String readTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(inputreader);
String line;
StringBuilder stringBuilder = new StringBuilder();
try
{
while (( line = bufferedreader.readLine()) != null)
{
stringBuilder.append(line);
stringBuilder.append('\n');
}
}
catch (IOException e)
{
return null;
}
return stringBuilder.toString();
}
任何人都可以帮助我所以,在第一个活动中单击按钮,您称之为意图启动第二个活动。如果您希望在第一个活动中选择资源id,那么我建议您使用如下内容
Button button = (Button) fragmentView.findViewById(R.id.button_id);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("resource_id", R.raw.books); //R.raw.books or any other resource you want to display
startActivity(intent);
}
});
int resourceId = getIntent().getIntExtra("resource_id");
然后在你的第二个活动中,你会得到这样的数据
Button button = (Button) fragmentView.findViewById(R.id.button_id);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("resource_id", R.raw.books); //R.raw.books or any other resource you want to display
startActivity(intent);
}
});
int resourceId = getIntent().getIntExtra("resource_id");
您使用此
resourceId
而不是R.raw.books
请使用下面的代码从raw文件夹读取文件数据
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.books);
byte[] b = new byte[in_s.available()];
in_s.read(b);
textView.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
textView.setText("Error: can't show help.");
}