我是Android / java的新手,并且遇到了我的第一个难题。

我试图根据用户是否登录来有条件地更改开始视图(我已经在这里设置了is_logged_in,以更简单地说明问题)。

非常感谢。

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        boolean is_logged_in = false;

        if(is_logged_in) {
            setContentView(R.layout.activity_main);
        } else {
            menu_sign_up(); // How would I pass the View?
        }
    }

    // Doesn't work, at least when called inside of MainActivity's onCreate
    public void menu_sign_up(/* View view */) {
        Intent intent = new Intent(this, SignUp.class);
        startActivity(intent);
    }

    // Example of a working method, at least when called from android:onClick in XML
    public void menu_sign_in(View view) {
        Intent intent = new Intent(this, SignIn.class);
        startActivity(intent);
        overridePendingTransition(0,0);
    }
}

public class SignUp extends MainActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_up);
    }

    // ...
}


*****截断的堆栈跟踪低于*******(adb logcat *:W)

W/ActivityManager(19583): Activity idle timeout for HistoryRecord{40953fd8 com.example.digitalkarmaeclipse/.SignUp}
W/ActivityManager(): Activity idle timeout for HistoryRecord{}
W/ActivityManager(21900): Launch timeout has expired, giving up wake lock!
W/ActivityManager(21900): Activity idle timeout for HistoryRecord{40a23580 com.example.digitalkarmaeclipse/.MainActivity}
W/ActivityManager(21900): Activity idle timeout for HistoryRecord{40a2c6f8 com.example.digitalkarmaeclipse/.SignUp}
W/ActivityManager(21900): Activity idle timeout for HistoryRecord{40a30100 com.example.digitalkarmaeclipse/.SignUp}
W/ActivityManager(21900): Activity idle timeout for HistoryRecord{40a338e8 com.example.digitalkarmaeclipse/.SignUp}
W/ActivityManager(21900): Activity idle timeout for HistoryRecord{40a376e0 com.example.digitalkarmaeclipse/.SignUp}

最佳答案

您当前的应用程序结构没有多大意义。 SignUp也必须是一个活动吗?您可以使用AlertDialog做类似的事情。如果确实需要一个Activity然后将其扩展为Activity,则在这种情况下扩展HomeActivity并没有多大意义。

我也不喜欢将setContentView()放在逻辑语句中的想法。仅在创建活动时才调用onCreate()。因此,如果您开始SignUp活动,然后按返回按钮,则HomeActivity不会有布局。

编辑:就像Shark所说的那样,您似乎没有办法将数据从SignUp传递回HomeActivity。您应该尝试使用startActivityForResult(),然后在setResult()中使用SignUp来说明它是否成功。

关于java - Android:在onCreate内部启动 Intent 会导致无限循环/崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11991276/

10-10 23:02