Requirement
Application requirement is when the user installs and opens for the first time, he will be shown LoginActivity
and once he logs in successfully, he will be asked to enter 4 digit passcode
, to use in future, if application remains idle and phone gets locked.
Design
I've decided it to design both as in One Activity
i.e. MainActivity
and load contentView
of LoginActivity
on certain condition.
Code Part
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
isUserValid=false; //just for testing on initial screen i.e. Login
super.onCreate(savedInstanceState);
if(isUserValid) {
setContentView(R.layout.activity_main);
}
else{
setContentView(R.layout.activity_login);
}
}
@Override
protected void onResume(){
super.onResume();
if(isUserValid) {
setContentView(R.layout.activity_main);
}
else{
setContentView(R.layout.activity_login);
}
}
@Override
protected void onStart(){
super.onStart();
if(isUserValid) {
setContentView(R.layout.activity_main);
}
else{
setContentView(R.layout.activity_login);
}
}
LoginActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Attaching click event to button
Button btnValidate=(Button)findViewById(R.id.validate_code);
btnValidate.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
//Functionality
}
});
}
I am aware that I could have attached click event directly to button in activity_login.xml
but then it works only when we use setActivity()
instead of setContentView
and am supposed to use setContentView
here as I do not want user to navigate between these 2 views on click of back button. I've also tried to attach click event for button in onCreate
on MainActivity.java
under else condition as below:
@Override
protected void onCreate(Bundle savedInstanceState) {
isUserValid=false; //just for testing on initial screen i.e. Login
super.onCreate(savedInstanceState);
if(isUserValid) {
setContentView(R.layout.activity_main);
}
else{
setContentView(R.layout.activity_login);
//Attaching click event to button
Button btnValidate=(Button)findViewById(R.id.validate_code);
btnValidate.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
//Functionality
}
});
}
}
But that did not help. further, I went forward and tried to attach the event in both onStart
and onResume
states of both the activity, nevertheless, did not work. The click event is not at all triggered. I assure that button with that id
is present in activity_login.xml
. What is that am committing mistake here. I am not getting the functionality and am in just starting stage of learning Android. Hope to find some solution for this behavior.
public void btnValidate(View view){ Your Functionality goes here }