在Android中切换两个活动时,更改布局中的可见性TextView



我有一个应用程序,它在Android中每10秒切换一次不同布局的两个不同活动(带有简单文本的主活动和带有两个文本视图的第二活动(。

我想在第二个活动中第一次只显示第一个文本视图A,然后返回主活动,再次进入第二个"活动",但只显示第二个文本视图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>

以及在下面提供的两个Activities之间切换的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);
........
}

我的问题是,每次在两个活动之间切换时,如何更改两个textView的可见性。

要做到这一点,只需将一个变量(如果只有两个TextView,则可以是布尔值(传递给第二个活动。如果是true,则显示1st TextView如果是false,则显示2nd 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);
}

最新更新