【问题标题】:Android start Activity 2 but rest at MainActivityAndroid 启动 Activity 2 但在 MainActivity 休息
【发布时间】:2021-03-27 04:59:08
【问题描述】:

我有 MainActivity,它有一个打开 Activity 2 的按钮。Activity 2 中的所有内容都应该计算并运行,但用户应该在 MainActivity 上休息吗?我该怎么做?

我找到了一个解决方案,我不运行“setContentView()”但随后我的应用程序崩溃了。

【问题讨论】:

  • “但用户应该在 MainActivity 休息”是什么意思? ?解释更多
  • 您确定您不只是想创建一个运行特定代码并返回您的活动的第二类,而不是第二个活动吗?
  • Activity 2 将启动,但用户仍应看到 MainActivity 的按钮:
  • @MahmoudOmara 我明白了。但是第二个活动有一个地图,并且在代码中多次调用了地图。所以我考虑在后台播放第二个活动,但用户仍然看到 MainActivity。我不确定当没有显示地图时代码是否有效
  • 您不应该在背景中包含这样的地图,但要实现此解决方案,您应该考虑使用 Fragment 而不是 Activity 作为地图,并将宽度/高度设置为 0dp 或GONE 的可见性

标签: java android android-studio android-activity show


【解决方案1】:

您想更改应用程序的视图但不希望用户更改活动。

在带有 id 的 xml 文件中使用两种不同的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/first_view">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button1"
            android:id="@+id/button"
            android:background="#358a32" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/second_view"
        android:visibility="gone">
    </LinearLayout>
<LinearLayout>

然后点击按钮:

public class MainActivity extends Activity {
    boolean firstViewOff = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        Button button = (Button) findViewById(R.id.button1);
        LinearLayout first_view = (LinearLayout) findViewById(R.id.first_view);
        LinearLayout second_view = (LinearLayout) findViewById(R.id.second_view);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                firstViewOff = true;
                first_view.setVisibility(View.GONE);
                second_view.setVisibility(View.VISIBLE);
            }
        });
    }
    @override
    public void onBackPressed(){
      super.onBackPressed();
      if(firstViewOff){
        second_view.setVisibility(View.GONE);
        first_view.setVisibility(View.VISIBLE);
        firstViewOff = false;
      }
    }

}

为什么我附上后压:

因为当用户按下后它会直接显示firstview而不关闭,

【讨论】:

    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 2017-04-19
    • 2013-06-15
    • 1970-01-01
    相关资源
    最近更新 更多