AndroidStudio点击不同的3个textview,进入同一个activity但是textview分别显示不同的txt文件,写代码
时间: 2023-06-14 11:04:25 浏览: 83
首先,需要在xml文件中定义3个TextView,并为每个TextView设置点击事件。点击事件中启动同一个Activity,并传递不同的参数,以便在Activity中根据参数加载相应的txt文件。
在xml文件中定义3个TextView:
```
<TextView
android:id="@+id/tv1"
android:text="TextView 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"/>
<TextView
android:id="@+id/tv2"
android:text="TextView 2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"/>
<TextView
android:id="@+id/tv3"
android:text="TextView 3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"/>
```
然后,在Activity中获取传递的参数,并根据参数加载相应的txt文件。代码如下:
```
public class MyActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
textView = findViewById(R.id.textView);
String file = getIntent().getStringExtra("file");
if (file != null) {
try {
InputStream inputStream = getAssets().open(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
textView.setText(stringBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
最后,在Activity中为每个TextView设置点击事件,并传递不同的文件名参数。
```
TextView tv1 = findViewById(R.id.tv1);
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, MyActivity.class);
intent.putExtra("file", "file1.txt");
startActivity(intent);
}
});
TextView tv2 = findViewById(R.id.tv2);
tv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, MyActivity.class);
intent.putExtra("file", "file2.txt");
startActivity(intent);
}
});
TextView tv3 = findViewById(R.id.tv3);
tv3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, MyActivity.class);
intent.putExtra("file", "file3.txt");
startActivity(intent);
}
});
```
阅读全文