Reputation: 1751
I just started development in android and got stuck with this idea
I have created two activity one is the HomeActivity and other one is LoginActivity. I want to put minimal code in the HomeActivity and all other operations i want to put in another activity.
My use-case is i have put an onclick event on HomeActivity and the onclick method implementation i have written in LoginActivity. But i am unable to call the LoginActivity onclick method implementation. Also, both HomeActivity and LoginActivity are having the same layout (activity_main.xml)
The files are as follows:
HomeActivity.java
public class HomeActivity extends Activity {
private static String TAG = HomeActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
LoginActivity.java
public class LoginActivity extends Activity {
private static String TAG = LoginActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
public void onLogin(View view){
// some actions
TextView loginText = (TextView)findViewById(R.id.login);
}
}
activity_home.xml
<TextView
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/login_bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick = "onLogin"
/>
Both HomeActivity and LoginActivity are using the same layout activity_home. Is it correct and possible to do this in android. and secondly if it's possible how to invoke onLogin on LoginActivity so that i can set the text to the TextView.
Upvotes: 1
Views: 1098
Reputation: 13520
Create a custom class CustomActivity
that extends Activity
private class CustomActivity extends Activity
{
public void onLogin(View view)
{
TextView loginText = (TextView) findViewById(R.id.login);
}
}
and then extend LoginActivity
and HomeActivity
with CustomActivity
. This way onLogin
method will be available to both LoginActivity
and HomeActivity
and if you need to change what you do in onLogin
you can override it in any of the child classes.
If you are using the above method as-is make sure that the layout of both LoginActivity
and HomeActivity
have a TextView
with id login
Upvotes: 2