What should I define in the setContentView in MainActivity.java file? - android

I want to know what should come in the bolded part below.It shows me two options:
1.toolbar(The xml I created to add the code for the google appbar)
2.activity_main
The both seems to show no errors that why I want to know which one should I add.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.**toolbar**);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}

hi add like this,
public class YourActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.youractivity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
mTitle.setText("Contact Us");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
hope this will help you

As Bansal mentioned correctly, you must use activity_main in setContentView.
Your activity_main.xml will contain the toolbar. Inside the toolbar tag you must call the toolbar layout. It uses your toolbar.xml layout for your toolbar.

Related

Toolbar NavigationOnClick not work

Hello I have a problem with listen click on navigation icon on my toolbar:
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_48dp);
myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("navigation", "navigation");
}
});
I wrote this, but not work, it doesn't listen click and it doesn't log nothing.
Try this code and it will work.
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Some Title");
myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("navigation", "navigation");
}
});
I think the problem is with this line " myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_48dp);"
Edit:Tested the above code in 6.0,5.1 and it is working as expected.

Set toolbar for all Activities [duplicate]

This question already has answers here:
Use Toolbar across all activities (Android)
(2 answers)
Closed 2 years ago.
In my app I would like to make a unique toolbar for all activities except for mainActivity.
I have written this code for set Title and logo, but in toolbar I also have username logged.
So I have written in my dashboard activity this code:
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
assert myToolbar != null;
myToolbar.setLogo(R.mipmap.logo_big);
TextView usernameField = (TextView) findViewById(R.id.username);
try {
usernameField.setText(User.getInstance().getUsername());
} catch (JSONException e) {
e.printStackTrace();
}
And I made a layout that can be included in all xml files.
But How can I reuse this code in all my activities without copy and paste?
Is it wrong to make a singleton? or a utility class?
Thanks
You could create a base activity that runs the common code and have all other activities inherit from it:
// the base class
public abstract class BaseActivity extends AppCompatActivity
{
protected final void onCreate(Bundle savedInstanceState, int layoutId)
{
super.onCreate(savedInstanceState);
setContentView(layoutId);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
assert myToolbar != null;
myToolbar.setLogo(R.mipmap.logo_big);
TextView usernameField = (TextView) findViewById(R.id.username);
try {
usernameField.setText(User.getInstance().getUsername());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
// inheriting activity
public class SomeActivity extends BaseActivity
{
protected final void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState, R.layout.some_layout);
}
}
keep your code in one CustomActivity.
Where every required in your application extends CustomActivity .
Example:
CustomActivity extends Activity{
// your toolbar code
}
In your all activities extends CustomActivity.
Create a new activity called CustomActivity and a corresponding layout called activity_custom.xml :
<android.support.v4.widget.DrawerLayout
android:id="#+id/activity_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="#color/background_material_dark"
/>
<FrameLayout
android:id="#+id/activity_content"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/menu_base"/>
Open BaseActivity.java and make sure to remove setContentView(R.layout.activity_base) from the onCreate() method. and override the setContentView() method with your own implementation:
#Override
public void setContentView(int layoutResID) {
DrawerLayout fullView = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.activity_content);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Activity Title");
}
In your all activities extends CustomActivity.
You can do like this:
class BaseActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void initToolbar(int toolbarId)
{
Toolbar myToolbar = (Toolbar) findViewById(toolbarId);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
assert myToolbar != null;
myToolbar.setLogo(R.mipmap.logo_big);
}
}
class YourActivity extends BaseActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(your activity layout);
initToolbar(R.id.yourToolbarId);
}
}

How to show default button back (arrow) in toolbar?

I want to set programmatically button back to my toolbar. How can I get a default drawable icon?
What I should write bar.setNavigationIcon( HERE );
If I set app:navigationIcon="?attr/homeAsUpIndicator" to my toolbar, button is shown. But how to do it in code or even maybe how to get this attr in code?
P.S:
I don't want use setSupportActionBar(..).
Tanks.
Try it:
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_launcher);
toolbar.setTitle("");
Thanks
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
You can use SetupToolbar:
private void SetupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
You have to override the onCreateOptionsMenu()
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
setToolbar();
}
In setToolbar() method you have to set the back icon in the tool bar
private void setToolbar() {
Toolbar ftoolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
if (ftoolbar != null) {
ftoolbar.setNavigationIcon(R.drawable.icon_back);
ftoolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Provide the Action
}
});
}
}

Calling Toolbar on each Activity

My app has a toolbar that should be present on every view. Currently, I do the following in my onCreate() method for each Activity I have:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Does this need to be done in every onCreate() method in every Activity or is there a simpler way? Also, as a side question, how can I implement a "back" feature in the toolbar that takes the user back one action if they click it?
Create a Base class for Activity
public abstract class BaseActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
configureToolbar();
}
protected abstract int getLayoutResource();
private void configureToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
FragmentManager fm = getSupportFragmentManager();
if (fm != null && fm.getBackStackEntryCount() > 0) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
finish();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
And in each Activity extends this BaseActivity to get the ToolBar and implementing the back feature.
At last don't forget to include the ToolBar in each activity layout.
Edit:
Override that method getLayoutResource() in each Activity and pass the layout id.
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public int getLayoutResource() {
return R.layout.activity_main;
}
This is my implementation. It removes the need of the getLayoutResources() from the accepted answer and brings back the "setContentView()" in all activities as normal
public abstract class BaseActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected boolean useToolbar() {
return true;
}
#Override
public void setContentView(int layoutResID) {
View view = getLayoutInflater().inflate(layoutResID, null);
configureToolbar(view);
super.setContentView(view);
}
private void configureToolbar(View view) {
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
if (toolbar != null) {
if (useToolbar()) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
toolbar.setVisibility(View.GONE);
}
}
}
}
From here on you just extend BaseActivity. If you don't want a toolbar you will have to override the useToolbar().
Don't forget to add in activity.xml at the top
<include layout="#layout/toolbar" />
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</merge>
It depends on your implementation but if you want avoid boilerplate code you should use good programming OO.
An Example using Fragment.
public abstract class FragmentBase extends Fragment {
protected void settingsToolbar(View rootView) {
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
final ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
// TODO add your code and your requirements
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
I hope this can give you an idea.
If you have used Activity then Create BaseActivity that extends AppCompatActivity or ActionBarActivity(Deprecated) and move Toolbar code to BaseActivity.
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
If you have used Fragment then Create BaseFragment that extends Fragment and move Toolbar code to BaseFragment.
public class BaseFragment extends Fragment {
View main;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main = inflater.inflate(R.layout.fragment_about, container, false);
Toolbar toolbar = (Toolbar) main.findViewById(R.id.toolbar);
getActivity().setSupportActionBar(toolbar);
return main;
}
}
In main XML layout you have to add Toolbar xml code.
Now in every view(Activity) extends BaseActivity instead of AppCompatActivity or ActionBarActivity so you can get access Toolbar in every view.
public class YourActivity extends BaseActivity{
//your code
}
EDIT1:
main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:theme="#style/toolbarTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/green"
android:minHeight="?attr/actionBarSize" />
</RelativeLayout>
EDIT2:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
add these two lines below setSupportActionBar(toolbar); in BaseActivity.
I hope it helps!
Create a base activity and initialize your tool bar in this class. Now it can be extends to all other child activity.
FirtActivity extends BaseActivity
SecondActivity extends BaseActivity
In base activity toll bar back button click you can check like below mentioned way
if(this instance of FirstActivity){
//do stuff here
}else if(this instance of SecondActivity){
//do stuff here
}

Android navigation drawer always open on tablet

I have seen many examples around, but I could not understand how to have the navigation drawer, always open in the tablet. I'm using this navigation drawer https://github.com/kanytu/android-material-drawer-template. I will have to create another xml file? and in OnCreate () what kind of code I need to add?
public class MainActivity extends AppCompatActivity implements NavigationDrawerCallbacks {
private Toolbar mToolbar;
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getFragmentManager();
..
..
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
public void onResume() {
super.onResume();
}
}
I do not have the precise knowledge but a workaround could be to make a different xml file for large devices without the DrawerLayout so when it runs on a tablet it will return null and no other boolean will be neede in the code and this will make the coding part very simple :-) kudos !

Categories

Resources