简体   繁体   English

Android 启动 Activity 2 但 rest 在 MainActivity

[英]Android start Activity 2 but rest at MainActivity

I have MainActivity which has got a button that opens Activity 2. Everything from Activity 2 should be calculated and be run but the user should rest at MainActivity?我有 MainActivity,它有一个打开 Activity 2 的按钮。应该计算并运行 Activity 2 中的所有内容,但用户应该在 MainActivity 中使用 rest? How do I do this?我该怎么做呢?

I found a solution where I dont run the "setContentView()" but then my app crashes.我找到了一个解决方案,我不运行“setContentView()”但随后我的应用程序崩溃了。

You want to change the view of application but does not want the user to change activity.您想更改应用程序的视图但不希望用户更改活动。

Use two different layout in xml file with id:在具有 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>

Then onclick of button:然后按钮的onclick:

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;
      }
    }

}

Why i attached backpressed:为什么我附上背压:

Because when user backpress then it will just directly show firstview without closing,因为当用户回压时,它只会直接显示 firstview 而不会关闭,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM