如何从不同的活动类设置onclicklistener?

时间:2017-12-23 08:16:45

标签: java android onclicklistener

如何设置属于不同活动的按钮的onClickListener? 我正在使用sharedPreferences,我想在不同的活动上创建一个注销按钮。在启动时打开的活动不应该有注销按钮。这就是我没有在个人资料活动中拥有所有sharedPreferences代码的原因。

HomeActivity类

//UserSessionManager class
UserSessionManager session;

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

    //start new activity when fab is clicked
    final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), Profile.class);
            startActivity(intent);
        }
    });

    session = new UserSessionManager(getApplicationContext());

    //check if user is logged in
    //if the user is not logged in
    if (session.checkLogin()) {
        finish();
    }

    HashMap<String, String> user = session.getUserDetails();

    //get variables
    String username = user.get(UserSessionManager.KEY_USERNAME);
    String age = user.get(UserSessionManager.KEY_AGE);
    String firstName = user.get(UserSessionManager.KEY_FIRSTNAME);


    EditText etUsername = (EditText) findViewById(R.id.etEmail);
    EditText etAge = (EditText) findViewById(R.id.etAge);

我希望注销按钮位于个人资料活动中。

以下是个人资料类

Button bLogOut;
UserSessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
}
public void sendSession(final UserSessionManager userSession) {
    bLogOut = (Button)findViewById(R.id.bLogOut);

    bLogOut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            userSession.logoutUser();
        }
    });
}

在做了很多不同的事情之后,我创建了send session方法,它接收来自HomeActivity类的会话变量作为参数。我还有一个nullpointerexception

3 个答案:

答案 0 :(得分:1)

在HomeActivity.class中创建一个接收器,如下所示,

public BroadcastReceiver logoutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            /Do what ever you want.
        }
    };

现在在HomeActvity.class中注册和取消注册您的接收器

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter intentFilter = new IntentFilter("com.saim.logoutReceiver");
        registerReceiver(logoutReceiver, intentFilter);

    }

    @Override
    protected void onDestroy() {
        try {
            super.onDestroy();
            unregisterReceiver(logoutReceiver);
        } catch (IllegalArgumentException i) {

        }
    }

现在只需从这样的任何活动中发送你的广播

sendBroadcast(new Intent("com.saim.logoutReceiver"));

答案 1 :(得分:0)

使用onActivityResult处理注销按钮操作:

HomeActivity Class:

/* keep this static final variables on a separate file */
public static final int LOGOUT_ACTION = 1;
public static final int REQUEST_LOGOUT = 2;
public static final int RESULT_LOGOUT = 3;
/* ============== */


 //start new activity when fab is clicked
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(this, ProfileActivity.class);
        startActivityForResult(intent, IntentUtil.REQUEST_LOGOUT);
    }
});


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_LOGOUT && resultCode == RESULT_LOGOUT) {
        //Handle logout here
    }

ProfileActivity类:

bLogOut.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        setResult(RESULT_LOGOUT, intent);
    }
});

答案 2 :(得分:0)

我通常如何处理登录和注销是为了做这种类型的模式。

我检查用户是否在启动时登录,然后启动我的身份验证活动。如果用户未登录,我会将用户登录到登录活动,直到他们登录为止。

MainActivity - (需要登录) - &gt; AuthenticationActivity - &gt; (RESULT_OK或RESULT_CANCELLED) - &gt;如果RESULT_CANCELLED,MainActivity会重新启动AuthenticationActivity。如果是RESULT_OK,则继续让您的用户使用您的应用。

在onCreate()中,将会话代码保存在那里以检查用户是否登录并不是一个坏主意。从另一个Activity返回MainActivity并发现用户未登录后,您可以将其返回到身份验证活动。

有一点需要注意,你应该在登录Activity中覆盖onBackPressed(),这样用户就不会意外地回到MainActivity。

样品:

MainActivity

public class MainActivity extends AppCompatActivity {

    private boolean isAuthenticated = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (/* User not logged in */) {
            Intent intent = new Intent(MainActivity.this, AuthenticationActivity.class);
            startActivityForResult(intent, AUTHENTICATION_REQ_CODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AUTHENTICATION_REQ_CODE) {
            if (resultCode == RESULT_CANCELED) {
                Intent intent = new Intent(MainActivity.this, AuthenticationActivity.class);
                startActivityForResult(intent, AUTHENTICATION_REQ_CODE);

                // User has cancelled login, redirect back to auth
            }
            else if (resultCode == RESULT_OK) {
                // User has logged in
                isAuthenticated = true;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}

AuthenticationActivity

public class AuthenticationActivity extends AppCompatActivity {

    Button loginButton;

    @Override
    public void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Do all your checks and if it all goes well, set result to RESULT_OK and finish to
                // MainActivity
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        finish();

        super.onBackPressed();
    }
}