Reputation: 98
I have Action bar
and a lot of different Activity
, its working, but I don't want to add code in every Activity
. How to add one code in one Activity
that will work in every Activity
? I expect to write only one code in one Activity
for all activities.
My main activity:
package ua.in.masterpc.technoguide;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ImageButton;
public class IconsMain extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icons_main);
ImageButton myImageButton = findViewById(R.id.iconPC);
myImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intentLoadNewActivity = new Intent(IconsMain.this, PCProblems.class);
startActivity(intentLoadNewActivity);
}
});
}
@Override//start menu code
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.bar_menu, menu);
return true;
}//end menu code
}
Thank you for answers!
Upvotes: 0
Views: 1021
Reputation: 133
Create a layout say, toolbar_layout, and add the the code for your layout, then include the layout in all your activities:
Upvotes: 0
Reputation: 254
create a baseActivity
add function inside it to initialize the toolbar and customize it as you like
open class BaseActivity : AppCompatActivity() {
protected fun initializeToolbar() {
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
}
}
create toolbar_main.xml
extends the baseActivity
in any activty after including the toolbar_main.xml
as <include layout="@layout/toolbar_main" />
class MainActivity : BaseActivity(){
}
and call the function you created in baseActivity
.
Upvotes: 0
Reputation: 1265
You can create class named BaseActivity
which will extend AppCompatActivity
and put there the code and functionality you want to use in every other Activity
. Then in every of your activities, you will extend BaseActivity
instead of AppCompatActivity
. By doing that you can avoid duplicating your code. Remember that you will have to put ActionBar
in every activity .xml
layout file.
Upvotes: 1