我想设置我的代码,当我单击列表视图中的一行时,它会从文本文件(来自记事本或 Access)返回文本。这是可能的还是需要不同的格式。
这是我到目前为止的代码,我相信它应该只是从文件中提取的一两行代码。这是我的主要活动代码:`
Toolbar toolbar;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
listView=(ListView) findViewById(R.id.listView);
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.Materials));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent= new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("MaterialName", listView.getItemAtPosition(i).toString());
startActivity(intent);
}
});
listView.setAdapter(mAdapter);
}
这是我的第二个活动代码:
`
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mToolbar = (Toolbar) findViewById(R.id.toolbar1);
material = (TextView) findViewById(R.id.textView);
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
mToolbar.setTitle(bundle.getString("MaterialName"));
if(mToolbar.getTitle().toString().equalsIgnoreCase("4140")){
//how do I get it to return the information from a text file
}
}
}`
查看答案中的链接后,我的第二个活动现在看起来像这样:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("4140.txt")));
String mLine;
while ((mLine = reader.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error reading file!", Toast.LENGTH_LONG).show();
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
TextView output= (TextView) findViewById(R.id.toolbar1);
output.setText((CharSequence)text);
}
}
}
当我运行模拟器时,我的主要活动正确出现。 我项目的主要活动
当我单击列表值 4140 而不是使用工具栏和带有我文件中的文本的 textview 显示第二个活动时,它停止工作。
另外我似乎遗漏了我想将文本文件链接到特定的列表值。当我对图像执行此操作时,当我单击列表值时,我在第二个活动上的工具栏重复了该列表值,然后根据我的工具栏所说的内容,它从我的可绘制文件中提取了正确的图像。似乎我缺少将每个列表值链接到其特定且正确的文本文件的部分。