简体   繁体   English

需要帮助切换活动

[英]Need help switching between activities

I'm VERY new at Android Studio so I ask kindly for an explanation on beginners level :) 我在Android Studio上非常新,所以我要求初学者级别的解释:)

I'm creating an app called SyncZ and I have a login screen created, I need to make it so that when I press 'Sign in or register' it goes to my activity_main.xml 我正在创建一个名为SyncZ的应用程序,我创建了一个登录屏幕,我需要这样做,以便当我按下“登录或注册”时,它会转到我的activity_main.xml

I started by creating a blank activity and later added a login activity, I then made the activity_login.xml to be main so that the login menu would come first when starting the app. 我开始创建一个空白活动,然后添加了一个登录活动,然后我将activity_login.xml设为main,以便在启动应用程序时首先登录菜单。

So my real question is, how can I switch from my activity_login to activity_main with button email_sign_in_button 所以我真正的问题是,如何通过按钮email_sign_in_button从我的activity_login切换到activity_main

Here are my codes (XML and Java) I'm very sorry if it's too much text, I hope you can work it out :) 这是我的代码(XML和Java)如果文本太多,我很抱歉,我希望你能解决它:)

AndroidManifest.xml AndroidManifest.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</RelativeLayout>

activity_login.xml activity_login.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.helloworld.LoginActivity"
>

<!-- Login progress -->
<ProgressBar
    android:id="@+id/login_progress"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="470dp"
    android:layout_height="470dp"
    android:layout_marginBottom="8dp"
    android:visibility="gone"/>

<LinearLayout
    android:id="@+id/email_login_form"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:weightSum="1">

    <ImageView
        android:layout_width="300dp"
        android:layout_height="160dp"
        android:id="@+id/imageView"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/syncz"
        android:layout_marginTop="50dp"
        android:layout_marginBottom="75dp" />

    <TextView
        android:layout_width="79dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Login:"
        android:id="@+id/textView"
        android:textStyle="bold" />

    <AutoCompleteTextView
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/prompt_email"
        android:inputType="textEmailAddress"
        android:maxLines="1"
        android:singleLine="true"
        android:layout_marginTop="16dp"
        android:textStyle="italic"
        android:layout_marginBottom="10dp" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:imeActionId="@+id/login"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionUnspecified"
        android:inputType="textPassword"
        android:maxLines="1"
        android:singleLine="true"
        android:textStyle="italic" />

    <Button
        android:id="@+id/email_sign_in_button"
        style="?android:textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="15dp"
        android:text="@string/action_sign_in"
        android:layout_weight="0.11"
        android:textSize="25dp"
        android:onClick="sendMessage" />/>
</LinearLayout>

</LinearLayout>

activity_main.xml activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</RelativeLayout>

LoginActivity.java LoginActivity.java

package com.example.administrator.helloworld;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
 * A login screen that offers login via email/password.
*/
public class LoginActivity extends Activity implements LoaderCallbacks<Cursor>{
/**
 * A dummy authentication store containing known user names and passwords.
 * TODO: remove after connecting to a real authentication system.
 */
private static final String[] DUMMY_CREDENTIALS = new String[]{
        "foo@example.com:hello", "bar@example.com:world"
};
/**
 * Keep track of the login task to ensure we can cancel it if requested.
 */
private UserLoginTask mAuthTask = null;

// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // Set up the login form.
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
    populateAutoComplete();

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        }
    });

    Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
    mEmailSignInButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptLogin();
            Intent intent= new Intent(LoginActivity.this,MainActivity.class);
            startActivity(intent);
        }
    });

    mLoginFormView = findViewById(R.id.login);
    mProgressView = findViewById(R.id.login_progress);
}

private void populateAutoComplete() {
    if (VERSION.SDK_INT >= 14) {
        // Use ContactsContract.Profile (API 14+)
        getLoaderManager().initLoader(0, null, this);
    } else if (VERSION.SDK_INT >= 9) {
        // Use AccountManager (API 8+)
        new SetupEmailAutoCompleteTask().execute(null, null);
    }
}



/**
 * Attempts to sign in or register the account specified by the login form.
 * If there are form errors (invalid email, missing fields, etc.), the
 * errors are presented and no actual login attempt is made.
 */
public void attemptLogin() {
    if (mAuthTask != null) {
        return;
    }

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;


    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt login and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        showProgress(true);
        mAuthTask = new UserLoginTask(email, password);
        mAuthTask.execute((Void) null);
    }
}
private boolean isEmailValid(String email) {
    //TODO: Replace this with your own logic
    return email.contains("@");
}

private boolean isPasswordValid(String password) {
    //TODO: Replace this with your own logic
    return password.length() > 4;
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new CursorLoader(this,
            // Retrieve data rows for the device user's 'profile' contact.
            Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

            // Select only email addresses.
            ContactsContract.Contacts.Data.MIMETYPE +
                    " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                                                                 .CONTENT_ITEM_TYPE},

            // Show primary email addresses first. Note that there won't be
            // a primary email address if the user hasn't specified one.
            ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    List<String> emails = new ArrayList<String>();
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        emails.add(cursor.getString(ProfileQuery.ADDRESS));
        cursor.moveToNext();
    }

    addEmailsToAutoComplete(emails);
}

@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {

}

private interface ProfileQuery {
    String[] PROJECTION = {
            ContactsContract.CommonDataKinds.Email.ADDRESS,
            ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
    };

    int ADDRESS = 0;
    int IS_PRIMARY = 1;
}

/**
 * Use an AsyncTask to fetch the user's email addresses on a background thread, and update
 * the email text field with results on the main UI thread.
 */
class SetupEmailAutoCompleteTask extends AsyncTask<Void, Void, List<String>> {

    @Override
    protected List<String> doInBackground(Void... voids) {
        ArrayList<String> emailAddressCollection = new ArrayList<String>();

        // Get all emails from the user's contacts and copy them to a list.
        ContentResolver cr = getContentResolver();
        Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                null, null, null);
        while (emailCur.moveToNext()) {
            String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract
                    .CommonDataKinds.Email.DATA));
            emailAddressCollection.add(email);
        }
        emailCur.close();

        return emailAddressCollection;
    }

    @Override
    protected void onPostExecute(List<String> emailAddressCollection) {
       addEmailsToAutoComplete(emailAddressCollection);
    }
}

private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
    //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
    ArrayAdapter<String> adapter =
            new ArrayAdapter<String>(LoginActivity.this,
                    android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

    mEmailView.setAdapter(adapter);
}

/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

    private final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.

        try {
            // Simulate network access.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return false;
        }

        for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }

        // TODO: register the new account here.

        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled() {
        mAuthTask = null;
        showProgress(false);
    }
}
}

MainActivity.java MainActivity.java

package com.example.administrator.helloworld;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}
  • Edit - Added Logcat Dropbox 编辑 - 添加了Logcat Dropbox
  • Edit - Updated all codes. 编辑 - 更新了所有代码。 Errors found via logcat in LoginActivity.java (line 177, 151 and 82) 通过LoginActivity.java中的logcat找到的错误(第177,151和82行)

Error line 82: 错误行82:

78 Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
79   mEmailSignInButton.setOnClickListener(new OnClickListener() {
80      @Override
81      public void onClick(View view) {
82          attemptLogin();
83          Intent intent= new Intent(LoginActivity.this,MainActivity.class);
84          startActivity(intent);
85      }
86 });

Error line 151: 错误行151:

144 if (cancel) {
145     // There was an error; don't attempt login and focus the first
146     // form field with an error.
147     focusView.requestFocus();
148 } else {
149     // Show a progress spinner, and kick off a background task to
150     // perform the user login attempt.
151     showProgress(true);
152     mAuthTask = new UserLoginTask(email, password);
153     mAuthTask.execute((Void) null);
154 }

Error line 177: 错误行177:

177 mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
178     mLoginFormView.animate().setDuration(shortAnimTime).alpha(
179             show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
180         @Override
181         public void onAnimationEnd(Animator animation) {
182             mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
183         }
184 });

In your login activity write this code: this will switch from LoginActivity to MainActivity 在您的登录活动中编写此代码:这将从LoginActivity切换到MainActivity

startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();

in Android you can switch between Activities using Intent's. 在Android中,您可以使用Intent在“活动”之间切换。 You define an Intent that, when activated, takes the user of your app to another activity (called an explicit Intent). 您定义一个Intent,在激活时,将您的应用程序的用户带到另一个活动(称为显式Intent)。 You can use Intents to pass Information (eg Objects) between the Activities of you app. 您可以使用Intents在应用程序的活动之间传递信息(例如对象)。

In a nutshell, how to use an Intent: 简而言之,如何使用Intent:

  1. Instantiate a new Intent providing it with a Context (usually your current Activity this) and the class Object of the target Activity (MainActivity.class) 实例化一个新的Intent,为它提供一个Context(通常是你当前的Activity)和目标Activity的类Object(MainActivity.class)
  2. If you want the Intent to transport Data to your new Activity attach the data to your intent instance using its putExtra() Methods. 如果您希望Intent将数据传输到新Activity,请使用其putExtra()方法将数据附加到您的intent实例。 This basically works like a Map. 这基本上像地图一样工作。 You can access the attached data in your target Activity using the same key that you stored the stuff with in the first place. 您可以使用与存储内容相同的密钥来访问目标Activity中的附加数据。
  3. Call startActivity() in your old Activity 在旧的Activity中调用startActivity()
  4. In your new Activity (MainActivity) extract the data from your Intent by getStringExtra() 在新的Activity(MainActivity)中,通过getStringExtra()从Intent中提取数据

One thing I found misleading when starting out was the connection between the android's activity lifecycle and the navigational facilities. 我在开始时发现误导的一件事是android的活动生命周期和导航设施之间的联系。 Eg you have to think about whether you want to start new instances of your activities when the user presses the button or whether you want to keep and reuse instances, etc. 例如,您必须考虑在用户按下按钮时是否要启动活动的新实例,或者是否要保留和重用实例等。

In addition to the basic navigational features of explicit Intents you can also use so called implicit Intents to provide access to App independent Android functionality eg write an email,... 除了显式Intents的基本导航功能之外,您还可以使用所谓的隐式Intent来提供对App独立Android功能的访问,例如写一封电子邮件,......

A more in depth tutorial is found here: http://developer.android.com/training/basics/firstapp/starting-activity.html 这里有一个更深入的教程: http//developer.android.com/training/basics/firstapp/starting-activity.html

If you want to know it all check this link to the Google API Doc for Intents: http://developer.android.com/reference/android/content/Intent.html 如果您想了解所有内容,请查看指向Google API Doc for Doc的链接: http//developer.android.com/reference/android/content/Intent.html

Hope that helps. 希望有所帮助。 Markus 马库斯

The best way to move between activities is usually using Intents (not sure if you have seen these). 在活动之间移动的最佳方式通常是使用Intents(不确定您是否已经看过这些)。 There are plenty resources regarding them such as this one: http://www.vogella.com/tutorials/AndroidIntent/article.html . 有很多关于它们的资源,例如: http//www.vogella.com/tutorials/AndroidIntent/article.html This guy has some really cool tutorials for beginners. 这个人有一些非常酷的初学者教程。 Basically what will happen is in your onClickListener method will pass an intent and start an activity with that intent. 基本上会发生什么是在你的onClickListener方法中将传递一个意图并启动具有该意图的活动。 The intent helps take info across activities, although they can be used for a variety of cool built in tasks as well such as photo selection. 意图有助于跨活动获取信息,尽管它们可用于各种很酷的内置任务,例如照片选择。 I hope this helps. 我希望这有帮助。

 Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent= new Intent(LoginActivity.this,MainActivity.class);
        startActivity(intent);
    }
});

The following code starts the activity: 以下代码启动活动:

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startaActivity(intent);

However, if you are going to pass data to MainActivity, you can use putExtra() ; 但是,如果要将数据传递给MainActivity,则可以使用putExtra() ;

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("myData", the data here);
startActivity(intent);

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

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