我想在第一个活动中单击按钮,在第二个活动中将原始资源中的文本加载到textview中。我认为可以通过putextra
,getextra
方法实现。我对textview的文本阅读器代码就是这个。
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();
}
任何人都可以帮助我
答案 0 :(得分:2)
请使用以下代码从原始文件夹中读取文件数据。
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.");
}
答案 1 :(得分:1)
因此,在按钮上单击第一个活动,您将调用意图启动第二个活动。如果您希望在第一个活动中选择资源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