java - 在Android中的两个活动之间切换时更改布局中的可见性TextView
问题描述
我有一个应用程序,在 Android 中每 10 秒在两个不同的活动(带有简单文本的主活动和带有两个 TextViews 的第二个活动)之间切换,具有不同的布局。
我想在第二个活动中第一次只显示第一个 textView A,然后返回到 MainActivity 并再次导致第二个活动但只显示第二个 textView B。
activity_second.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="255dp"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_purple"
android:orientation="horizontal">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="A"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textSize="65sp" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_orange_light"
android:orientation="horizontal">
<TextView
android:id="@+id/textViewB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="B"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textSize="65sp" />
</LinearLayout>
</LinearLayout>
下面提供了在两个活动之间切换的 java 代码。
Second_activity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 10000);
........
}
我的问题是每次在两个活动之间切换时如何更改两个文本视图的可见性。
解决方案
要做到这一点您可以将一个变量(如果只有 2 个 TextView,它可以是布尔值)传递给第二个活动。如果是true
显示第false
2 个 TextView,则显示第 1 个 TextView。
要有意传递价值,请使用:
Boolean value = true; //set this if You want to show 1st or 2nd textbox
Intent i = new Intent(CurrentActivity.this, NewActivity.class);
i.putExtra("key", value);
startActivity(i);
要检索值:
Bundle extras = getIntent().getExtras();
if (extras != null) {
Boolean value = extras.getBoolean("key");
//The key argument here must match that used in the other activity
}
当您value
刚刚设置了 TextViews 的可见性时:
if (value)
{
textView1.setVisibility(TextView.VISIBLE);
textView2.setVisibility(TextView.GONE);
}
else
{
textView1.setVisibility(TextView.GONE);
textView2.setVisibility(TextView.VISIBLE);
}
推荐阅读
- python - 带有 ros-gazebo 的 pydrake 控制器
- html - 如何使表格的第二列更宽?
- python - 以下算法的空间复杂度
- lua - 如何在 Love2D 中播放部分音频?
- r - 基于函数在数据框列表中创建一列
- r - 如何调整R中保存的格式化表中的行空间
- pine-script - Tradingview上的回测问题,有没有办法扩展它?
- reactjs - 您如何在客户端中正确存储包含刷新令牌的 httponly cookie?
- c# - 为什么 S3 在使用 StreamReader 进行后续调用后检索速度会提高?
- python - Groupby Pandas,根据日期差异计算多列