Android Multiline Toolbar Title - java

I have a Toolbar that when in landscape mode isn't as wide as usual, but it has more height than usual and for that reason I want to set the title to be multiline (2 lines to be precise) when it is in landscape. I have tried some things where I put a TextView inside of the Toolbar, but when I try to access the TextView to set it's title (since the the title is variable) I get a NullPointer after using findViewById.
Here is some code of the current situation (without multiline):
#Override
protected void onResume() {
super.onResume();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = (int)( size.x * 0.37);
int height = Math.round(size.x * 0.63f * 0.25f);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width,height);
toolbar.setLayoutParams(params);
}
if (executeOnResume) {
currentProject = getIntent().getParcelableExtra("Project");
getSupportActionBar().setTitle("This is a pretty long piece of text, I hope it fits");
// A lot of irrelevant code...
//...
//...
} else { loadStuff();}
}
And here is the toolbar xml:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar2"
android:title="#string/menuLabel1a"
app:layout_widthPercent="37%"
app:layout_heightPercent="26%"
android:gravity="top"
app:titleTextAppearance="#style/toolbarTitleText"
android:background="#color/greyLight"
android:theme="#style/AppTheme.AppBarOverlay"
app:popupTheme="#style/AppTheme.PopupOverlay" />

Try this :
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="#dimen/double_height_toolbar"
android:gravity="top"
app:titleTextAppearance="#style/toolbarTitleText"
android:background="#color/greyLight"
android:theme="#style/AppTheme.AppBarOverlay"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:id="#+id/product_details_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:title="#string/menuLabel1a"
android:paddingTop="#dimen/padding_normal"
style="#android:style/TextAppearance.Holo.Widget.ActionBar.Title.Inverse"
android:maxLines="2" />
</android.support.v7.widget.Toolbar>
Other Solution is for ActionBar
The default TextView of the ActionBar does not support line wrapping, and there is no exposed method to set it to wrap. So you can create a flexible layout, like this: action_bar_title_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/action_bar_title"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:gravity="center_vertical"
android:ellipsize="end"
android:maxLines="2"/>
</LinearLayout>
Then set this as the custom layout on your ActionBar:
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.action_bar_title_layout);
((TextView) findViewById(R.id.action_bar_title)).setText(
"This is a long text title that will wrap to multiple lines, when necessary.");

Found this solution who was work for me :
fun Toolbar.disableTitleSingleLine() {
for (i in 0..childCount) {
val child = getChildAt(i)
if (child is TextView) {
child.isSingleLine = false
}
}
}
According Toolbar implementation, the title TextView is created when text been set.
It's important to call this extension after title set.

Related

change the color of toolbar when it is collapsed in android [duplicate]

After the user scrolls down the screen, the image in the CollapsingToolbarLayout disappears and is left with a toolbar with the back button, content title, and settings menu. I want to know how to change the background color of that toolbar only when its in a 'collapsed' state.
The action I am referring to is similar to this where the toolbar background color changes to green:
Below the CollapsingToolbarLayout I have a NestedScrollView with CardViews
I think you're after app:contentScrim.
<android.support.design.widget.CollapsingToolbarLayout
...
app:contentScrim="?attr/colorPrimary">
<!-- Toolbar and ImageView here -->
</android.support.design.widget.CollapsingToolbarLayout>
First remove
app:contentScrim="?attr/colorPrimary">
from CollapsingToolbarLayout
Add library
compile 'com.android.support:palette-v7:23.2.1'
And add below code in java code
Bitmap bitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.ny);
Palette.generateAsync(bitmap,
new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
Palette.Swatch vibrant =
palette.getVibrantSwatch();
int mutedColor = palette.getVibrantSwatch().getRgb();
if (vibrant != null) {
// If we have a vibrant color
// update the title TextView
collapseToolbar.setBackgroundColor(mutedColor);
// mutedColor = palette.getMutedColor(R.attr.colorPrimary);
collapseToolbar.setStatusBarScrimColor(palette.getDarkMutedColor(mutedColor));
collapseToolbar.setContentScrimColor(palette.getMutedColor(mutedColor));
}
}
});
Just use CollapsingToolbarLayout XML attribute contentScrim to set Toolbar background color when it's in collapsed mode.
app:contentScrim="YOUR_TOOLBAR_COLOR"
Here is an Example:
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/img_group_photo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/anim_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
Hope this will help~
Maybe what you have been looking for is this :
myCollapsingToolbar.setContentScrimColor(getResources().getColor(R.color.my_color_id));
It worked for me and changed the color of the collapsingToolbar once it was collapsed to help me fit the main color of an image that was displayed when the collapsingToolbar was full scale. With this, the color can obviously be changed programatically!
I know I'm late, but I hope it could help.
You can use an AppBarLayout's offset listener and change the CollapsingTollbar attributes according to the desired behavior.
appBarLayout.addOnOffsetChangedListener { _, verticalOffSet ->
if (Math.abs(verticalOffSet) == appBarLayout.totalScrollRange) {
//Collapsed
toolBar.setBackgroundDrawable(ContextCompat.getDrawable(this,
R.drawable.last_revolut_gradient))
} else {
//Expanded
toolBar.setBackgroundColor(ContextCompat.getColor(this,
android.R.color.transparent))
}
}
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.header);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#SuppressWarnings("ResourceType")
#Override
public void onGenerated(Palette palette) {
Palette.Swatch vibrant =
palette.getVibrantSwatch();
if (vibrant != null) {
collapsingToolbar.setBackgroundColor(getResources().getColor(R.color.cpb_blue));
collapsingToolbar.setStatusBarScrimColor(getResources().getColor(R.color.cpb_blue));
collapsingToolbar.setContentScrimColor(getResources().getColor(R.color.cpb_blue));
}
}
});

Changing height of ListView spoils alignment

I have a fragment inside a ViewPager and am trying to dynamically change the height of a ListView depending on the size of the screen.
Here is the xml code for my fragment:
Fragment.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<RelativeLayout
android:id="#+id/rlDiscoveredDevice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tvSuggestBTOn">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvDiscoveredDevices"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:text="#string/text_list_discovered_devices"
/>
<ProgressBar
android:id="#+id/pbDiscoveredDevices"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/tvDiscoveredDevices"
android:layout_marginStart="16dp"
/>
<ListView
android:id="#+id/lstDiscoveredBTDevices"
android:layout_height="250dp"
android:layout_width="wrap_content"
android:divider="#android:color/transparent"
android:dividerHeight="#dimen/list_view_divider_height"
android:choiceMode="singleChoice"
android:listSelector="#color/list_item_selected"
android:layout_below="#+id/tvDiscoveredDevices"
android:layout_marginTop="#dimen/list_view_margin_top"
/>
</RelativeLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pairBT"
android:background="#drawable/ic_action_down"
android:layout_marginStart="134dp"
android:layout_below="#+id/rlDiscoveredDevice"
android:layout_alignParentStart="true"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/unpairBT"
android:background="#drawable/ic_action_up"
android:layout_below="#+id/rlDiscoveredDevice"
android:layout_toEndOf="#+id/pairBT"
android:layout_marginStart="73dp"
/>
<RelativeLayout
android:id="#+id/rlPairedDevice"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/pairBT">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvPairedDevices"
android:text="#string/text_list_paired_devices"
android:layout_alignParentStart="true"
/>
<ListView
android:id="#+id/lstPairedBTDevices"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:divider="#android:color/transparent"
android:dividerHeight="#dimen/list_view_divider_height"
android:choiceMode="singleChoice"
android:listSelector="#color/list_item_selected"
android:layout_below="#+id/tvPairedDevices"
android:layout_alignParentStart="true"
android:layout_marginTop="#dimen/list_view_margin_top"
/>
</RelativeLayout>
</RelativeLayout>
Here is my java code that I use to dynamically change the height:
DiscoveredDevice.java
public class DiscoveredDevice extends Fragment{
final String TAG = "DiscoverDevice Fragment";
private SharedPreferences appPrefs;
private BTActions btActions;
private ArrayList<BluetoothDevice> arrDiscoveredDevicesList;
private Set<BluetoothDevice> arrPairedDevicesList;
private ArrayAdapter<String> btDiscListArrayAdapter;
private ArrayAdapter<String> btPairedListArrayAdapter;
private String strDiscoveredListItemSelected = "";
private String strPairedListItemSelected = "";
private CommonFunctions cf;
private boolean blnIsFragmentLoaded = false;
// UI Objects
private TextView tvDiscoveredDevices;
private TextView tvPairedDevices;
private ListView lvDiscoveredList;
private ListView lvPairedDevicesList;
private ImageButton ibtnPair;
private ImageButton ibtnUnPair;
private ProgressBar pbDiscDevicesSpinner;
private TextView tvSuggestBTOn;
private ProgressBar pbLoading;
public DiscoveredDevice() {
btActions = new BTActions();
cf = new CommonFunctions();
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "Begin render of Discovered Device fragment...");
super.onCreate(savedInstanceState);
// Define variables
appPrefs = this.getActivity().getPreferences(Context.MODE_PRIVATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_discovered_device, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Define the lists on DiscoveredDevice fragment
btDiscListArrayAdapter = new ArrayAdapter<>(getContext(), R.layout.simple_row, R.id.simple_row_Txt);
btPairedListArrayAdapter = new ArrayAdapter<>(getContext(), R.layout.simple_row, R.id.simple_row_Txt);
// Define UI Objects
defineUIObjects();
// Position UI objects
positionUIObjects();
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
private void defineUIObjects() {
tvDiscoveredDevices = (TextView) getView().findViewById(R.id.tvDiscoveredDevices);
tvPairedDevices = (TextView) getView().findViewById(R.id.tvPairedDevices);
lvDiscoveredList = (ListView) getView().findViewById(R.id.lstDiscoveredBTDevices);
lvPairedDevicesList = (ListView) getView().findViewById(R.id.lstPairedBTDevices);
ibtnPair = (ImageButton) getView().findViewById(R.id.pairBT);
ibtnUnPair = (ImageButton) getView().findViewById(R.id.unpairBT);
tvSuggestBTOn = (TextView) getView().findViewById(R.id.tvSuggestBTOn);
pbDiscDevicesSpinner = (ProgressBar) getView().findViewById(R.id.pbDiscoveredDevices);
pbLoading = (ProgressBar) getView().findViewById(R.id.spin_kit_progress);
pbLoading.setIndeterminateDrawable(new DoubleBounce());
}
private void positionUIObjects() {
final ViewGroup vgDiscDevice = (ViewGroup) getView().findViewById(R.id.rlDiscoveredDevice);
final AtomicInteger aiLayoutHeight = new AtomicInteger();
Rect rect = new Rect();
// Get the window
Window win = getActivity().getWindow();
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Find height of AppBarLayout
AppBarLayout ablTabs = (AppBarLayout) getActivity().findViewById(R.id.ablTabs);
// Obtain the screen height & width
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int intScreenHeight = metrics.heightPixels;
int intScreenWidth = metrics.widthPixels;
Log.i(TAG, "Actual Screen Height = " + intScreenHeight + " Width = " + intScreenWidth);
// Set the height for Discovered Devices list
RelativeLayout.LayoutParams rlParams = (RelativeLayout.LayoutParams) getView().findViewById(R.id.rlDiscoveredDevice).getLayoutParams();
// Get height of Discovered Devices relative layout
int intDiscoveredDevicesRLHeight = (int)(Math.round((intScreenHeight - rect.top - ablTabs.getMeasuredHeight()) * 0.45));
Log.i(TAG, "Setting the height of Discovered Devices Relative layout as '" + intDiscoveredDevicesRLHeight + "'");
rlParams.topMargin = ablTabs.getMeasuredHeight();
rlParams.leftMargin = 50; // I DID THIS JUST TO CHECK IF THE LEFT MARGIN GETS MOVED TO THE RIGHT. THIS IS WHERE I NEED A BETTER WAY TO PROPERLY ALIGN THE LIST
rlParams.height = intDiscoveredDevicesRLHeight;
lvDiscoveredList.setLayoutParams(rlParams);
}
I want each list to occupy 45% of the screen(excluding the AppBarLayout). If you see the below screenshot, when I set the new height, the ListView goes out of alignment and part of it gets cuts to the left of the screen. I have set the Left margin to 50 to bring it into view.
[Screenshot]
I have placed 2 ListViews inside a RelativeLayouts so that they can be individually controlled as a whole. Am I doing something wrong here ?
I think you can achieve this with just xml, no dynamic resizing!
In your post you mentioned that you want the list views to each take 45% of the available height. Thus, I am assuming that the center content with the image views will take 10% of the height (though this approach will also work if they had a fixed height, I'll include that answer too at the bottom.
All you need to do is change your top level layout to a LinearLayout (with a vertical orientation), put your image views inside of a LinearLayout (with horizontal orientation), change some of the heights of your views and add layout_weight attributes to the two RelativeLayouts and the inner LinearLayout you will create. Here is an example of what your xml will look like:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<RelativeLayout
android:id="#+id/rlDiscoveredDevice"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_above="#+id/tvSuggestBTOn"
android:layout_weight="9">
<TextView
android:id="#+id/tvDiscoveredDevices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="#string/text_list_discovered_devices"
/>
<ProgressBar
android:id="#+id/pbDiscoveredDevices"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/tvDiscoveredDevices"
/>
<ListView
android:id="#+id/lstDiscoveredBTDevices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tvDiscoveredDevices"
android:divider="#android:color/transparent"
android:dividerHeight="#dimen/list_view_divider_height"
android:choiceMode="singleChoice"
android:listSelector="#color/list_item_selected"
android:background="#drawable/abc_list_selector_disabled_holo_dark"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:gravity="center"
android:layout_weight="2">
<ImageButton
android:id="#+id/pairBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_action_down"
/>
<ImageButton
android:id="#+id/unpairBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_action_up"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/rlPairedDevice"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvPairedDevices"
android:text="#string/text_list_paired_devices"
android:layout_alignParentStart="true"
/>
<ListView
android:id="#+id/lstPairedBTDevices"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="#dimen/list_view_divider_height"
android:choiceMode="singleChoice"
android:listSelector="#color/list_item_selected"
android:layout_below="#+id/tvPairedDevices"
android:layout_alignParentStart="true"
android:background="#drawable/abc_list_selector_disabled_holo_dark"
/>
</RelativeLayout>
</LinearLayout>
The important thing to note here is that the RelativeLayouts now have a weight of 9 each and the center linear layout has a weight of 2. Thus the space in the top level linear layout will be divided in that ratio, the RelativeLayouts will get 45% each and the LinearLayout will get 10%.
If you wanted the linear layout in the center to be wrap content instead of taking 10% of the screen (I would recommend this) then you could go ahead and assign it a height of wrap_content and remove the layout_weight attribute from it. The top level LinearLayout will then take the leftover height after allocating space for the center LinearLayout and divide it evenly between the two Relative layouts.
PS: (Heads up, you can probably use the xml I posted here. I set backgrounds on the list views to make it easy for me to see their sizes without data, make sure to remove those).
PPS: Note that this approach allows you to remove a lot of the layout positioning attributes that you had with a top level relative layout! This not only improves the cleanliness of your code, but also makes your UI more performant (Relative Layouts are less performant than other view groups, especially when nested).

How to center title in Toolbar via java file? [duplicate]

I'm trying to figure out the right way to use a custom font for the toolbar title, and center it in the toolbar (client requirement).
At the moment, i'm using the good old ActionBar, and I was setting the title to empty value, and using setCustomView to put my custom font TextView and center it using ActionBar.LayoutParams.
Is there a better way to do that? Using the new Toolbar as my ActionBar.
To use a custom title in your Toolbar all you need to do is remember is that Toolbar is just a fancy ViewGroup so you can add a custom title like so:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?android:attr/actionBarSize"
android:background="#color/action_bar_bkgnd"
app:theme="#style/ToolBarTheme" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:id="#+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
This means that you can style the TextView however you would like because it's just a regular TextView. So in your activity you can access the title like so:
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
This's just to help to join all pieces using #MrEngineer13 answer with #Jonik and #Rick Sanchez comments with the right order to help to achieve title centered easly!!
The layout with TextAppearance.AppCompat.Widget.ActionBar.Title :
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_gravity="center" />
</android.support.v7.widget.Toolbar>
The way to achieve with the right order:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
mTitle.setText(toolbar.getTitle());
getSupportActionBar().setDisplayShowTitleEnabled(false);
Please don't forget to upvote #MrEngineer13 answer !!!
Here is a sample project ToolbarCenterTitleSample
Hope to help somebody else ;)
The ToolBar title is stylable. Any customization you make has to be made in the theme. I'll give you an example.
Toolbar layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
style="#style/ToolBarStyle.Event"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="#dimen/abc_action_bar_default_height_material" />
Styles:
<style name="ToolBarStyle" parent="ToolBarStyle.Base"/>
<style name="ToolBarStyle.Base" parent="">
<item name="popupTheme">#style/ThemeOverlay.AppCompat.Light</item>
<item name="theme">#style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
<style name="ToolBarStyle.Event" parent="ToolBarStyle">
<item name="titleTextAppearance">#style/TextAppearance.Widget.Event.Toolbar.Title</item>
</style>
<style name="TextAppearance.Widget.Event.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<!--Any text styling can be done here-->
<item name="android:textStyle">normal</item>
<item name="android:textSize">#dimen/event_title_text_size</item>
</style>
we don't have direct access to the ToolBar title TextView so we use reflection to access it.
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = mToolBar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView) f.get(mToolBar);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
Define the following class:
public class CenteredToolbar extends Toolbar {
private TextView centeredTitleTextView;
public CenteredToolbar(Context context) {
super(context);
}
public CenteredToolbar(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public CenteredToolbar(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void setTitle(#StringRes int resId) {
String s = getResources().getString(resId);
setTitle(s);
}
#Override
public void setTitle(CharSequence title) {
getCenteredTitleTextView().setText(title);
}
#Override
public CharSequence getTitle() {
return getCenteredTitleTextView().getText().toString();
}
public void setTypeface(Typeface font) {
getCenteredTitleTextView().setTypeface(font);
}
private TextView getCenteredTitleTextView() {
if (centeredTitleTextView == null) {
centeredTitleTextView = new TextView(getContext());
centeredTitleTextView.setTypeface(...);
centeredTitleTextView.setSingleLine();
centeredTitleTextView.setEllipsize(TextUtils.TruncateAt.END);
centeredTitleTextView.setGravity(Gravity.CENTER);
centeredTitleTextView.setTextAppearance(getContext(), R.style.TextAppearance_AppCompat_Widget_ActionBar_Title);
Toolbar.LayoutParams lp = new Toolbar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
centeredTitleTextView.setLayoutParams(lp);
addView(centeredTitleTextView);
}
return centeredTitleTextView;
}
}
...and then just use it instead of regular Toolbar like this:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent">
<your.packagename.here.CenteredToolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:title="#string/reset_password_page_title"/>
<!-- Other views -->
</RelativeLayout>
You still need these 2 lines of code in your Activity (as with standard Toolbar):
Toolbar toolbar = (Toolbar) findViewByid(R.id.toolbar); // note that your activity doesn't need to know that it is actually a custom Toolbar
setSupportActionBar(binding.toolbar);
That's it! You don't need to hide the standard left-aligned title, don't need to duplicate the same XML code over and over, etc., just use CenteredToolbar like if it was default Toolbar. You can also set your custom font programatically since you now have direct access to the TextView. Hope this helps.
MaterialToolbar from Material Components 1.4.0-alpha02 now has the ability to center the toolbar's title by setting the titleCentered attribute to true:
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
style="#style/Widget.MaterialComponents.Toolbar.Primary"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:titleCentered="true" />
</com.google.android.material.appbar.AppBarLayout>
Here is title text dependant approach to find TextView instance from Toolbar.
public static TextView getToolbarTitleView(ActionBarActivity activity, Toolbar toolbar){
ActionBar actionBar = activity.getSupportActionBar();
CharSequence actionbarTitle = null;
if(actionBar != null)
actionbarTitle = actionBar.getTitle();
actionbarTitle = TextUtils.isEmpty(actionbarTitle) ? toolbar.getTitle() : actionbarTitle;
if(TextUtils.isEmpty(actionbarTitle)) return null;
// can't find if title not set
for(int i= 0; i < toolbar.getChildCount(); i++){
View v = toolbar.getChildAt(i);
if(v != null && v instanceof TextView){
TextView t = (TextView) v;
CharSequence title = t.getText();
if(!TextUtils.isEmpty(title) && actionbarTitle.equals(title) && t.getId() == View.NO_ID){
//Toolbar does not assign id to views with layout params SYSTEM, hence getId() == View.NO_ID
//in same manner subtitle TextView can be obtained.
return t;
}
}
}
return null;
}
No one has mentioned this, but there are some attributes for Toolbar:
app:titleTextColor for setting the title text color
app:titleTextAppearance for setting the title text appearance
app:titleMargin for setting the margin
And there are other specific-side margins such as marginStart, etc.
I use this solution:
static void centerToolbarTitle(#NonNull final Toolbar toolbar) {
final CharSequence title = toolbar.getTitle();
final ArrayList<View> outViews = new ArrayList<>(1);
toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT);
if (!outViews.isEmpty()) {
final TextView titleView = (TextView) outViews.get(0);
titleView.setGravity(Gravity.CENTER);
final Toolbar.LayoutParams layoutParams = (Toolbar.LayoutParams) titleView.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
toolbar.requestLayout();
//also you can use titleView for changing font: titleView.setTypeface(Typeface);
}
}
Without toolbar TextView we can customize font by using below code
getSupportActionBar().setDisplayShowTitleEnabled(false);
or
getActionBar().setDisplayShowTitleEnabled(false);
public void updateActionbar(String title){
SpannableString spannableString = new SpannableString(title);
spannableString.setSpan(new TypefaceSpanString(this, "futurastdmedium.ttf"),
0, spannableString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mToolbar.setTitle(spannableString);
}
public class TestActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test);
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
setSupportActionBar(toolbar);
customizeToolbar(toolbar);
}
public void customizeToolbar(Toolbar toolbar){
// Save current title and subtitle
final CharSequence originalTitle = toolbar.getTitle();
final CharSequence originalSubtitle = toolbar.getSubtitle();
// Temporarily modify title and subtitle to help detecting each
toolbar.setTitle("title");
toolbar.setSubtitle("subtitle");
for(int i = 0; i < toolbar.getChildCount(); i++){
View view = toolbar.getChildAt(i);
if(view instanceof TextView){
TextView textView = (TextView) view;
if(textView.getText().equals("title")){
// Customize title's TextView
Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
textView.setLayoutParams(params);
// Apply custom font using the Calligraphy library
Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-1.otf");
textView.setTypeface(typeface);
} else if(textView.getText().equals("subtitle")){
// Customize subtitle's TextView
Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
textView.setLayoutParams(params);
// Apply custom font using the Calligraphy library
Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-2.otf");
textView.setTypeface(typeface);
}
}
}
// Restore title and subtitle
toolbar.setTitle(originalTitle);
toolbar.setSubtitle(originalSubtitle);
}
}
Layout:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="#color/action_bar_bkgnd"
app:theme="#style/ToolBarTheme" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
Code:
Toolbar mToolbar = parent.findViewById(R.id.toolbar_top);
TextView mToolbarCustomTitle = parent.findViewById(R.id.toolbar_title);
//setup width of custom title to match in parent toolbar
mToolbar.postDelayed(new Runnable()
{
#Override
public void run ()
{
int maxWidth = mToolbar.getWidth();
int titleWidth = mToolbarCustomTitle.getWidth();
int iconWidth = maxWidth - titleWidth;
if (iconWidth > 0)
{
//icons (drawer, menu) are on left and right side
int width = maxWidth - iconWidth * 2;
mToolbarCustomTitle.setMinimumWidth(width);
mToolbarCustomTitle.getLayoutParams().width = width;
}
}
}, 0);
A very quick and easy way to set a custom font is to use a custom titleTextAppearance with a fontFamily:
Add to styles.xml:
<style name="ToolbarTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">16sp</item>
<item name="android:textColor">#FF202230</item>
<item name="android:fontFamily">#font/varela_round_regular</item>
</style>
In your res folder create a font folder (Ex: varela_round_regular.ttf)
Read the official guide to find out more https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
Solution that I used for this problem:
public static void applyFontForToolbarTitle(Activity a){
Toolbar toolbar = (Toolbar) a.findViewById(R.id.app_bar);
for(int i = 0; i < toolbar.getChildCount(); i++){
View view = toolbar.getChildAt(i);
if(view instanceof TextView){
TextView tv = (TextView) view;
if(tv.getText().equals(a.getTitle())){
tv.setTypeface(getRuneTypefaceBold(a));
break;
}
}
}
}
For center gravity I think it would be necessary to change layout params to match_parent horizontally and then:
tv.setGravity(Gravity.CENTER);
I don't know if anything changed in the appcompat library but it's fairly trivial, no need for reflection.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// loop through all toolbar children right after setting support
// action bar because the text view has no id assigned
// also make sure that the activity has some title here
// because calling setText() with an empty string actually
// removes the text view from the toolbar
TextView toolbarTitle = null;
for (int i = 0; i < toolbar.getChildCount(); ++i) {
View child = toolbar.getChildAt(i);
// assuming that the title is the first instance of TextView
// you can also check if the title string matches
if (child instanceof TextView) {
toolbarTitle = (TextView)child;
break;
}
}
I solved this solution , And this is a following codes:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order History"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="17sp"
android:textStyle="bold"
android:textColor="#color/colorWhite"
/>
</android.support.v7.widget.Toolbar>
And you can change title/label , in Activity, write a below codes:
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
mTitle.setText("#string/....");
You can use like the following
<android.support.v7.widget.Toolbar
android:id="#+id/top_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppThemeToolbar">
<TextView
android:id="#+id/pageTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</android.support.v7.widget.Toolbar>
With the Material Components, starting from the version 1.4.x as described in the doc you can use the MaterialToolbar.
Just add the attribute app:titleCentered and/or app:subtitleCentered attributes to true on your MaterialToolbar.
Something like:
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
app:titleCentered="true"
... />
With Compose using the Material3 package you can simply use the CenterAlignedTopAppBar:
CenterAlignedTopAppBar(
title = { Text("Centered TopAppBar") },
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
}
)
If you are using Compose and the Material2 package, there isn't a builtin component but you can customize the layout of content inside the TopAppBar as described in this answer.
Update from #MrEngineer13's answer: to align title center in any cases, including Hamburger icon, option menus, you can add a FrameLayout in toolbar like this:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="#color/action_bar_bkgnd"
app:theme="#style/ToolBarTheme" >
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:id="#+id/toolbar_title" />
</FrameLayout>
</android.support.v7.widget.Toolbar>
Now using Material Design 3 we can align the title in the center without doing extra work or without adding a text view in the toolbar
Added below dependencies in build.gradle file
implementation 'com.google.android.material:material:1.6.1'
To align the title in the center We need to use the below properly
app:titleCentered="true"
To align subtitles in the center we need to use the below property
app:subtitleCentered="true"
Sample Code
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="AskNilesh"
app:subtitle="Nilesh"
app:subtitleCentered="true"
app:menu="#menu/top_app_bar"
app:titleCentered="true"
app:navigationIcon="#drawable/ic_android_black_24dp" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
OUTPUT
Even though adding a text view to the toolbar can solve the problem of the restriction of title styling, there is an issue with it. Since we are not adding it to a layout, we do not have too much control over its width. We can either use wrap_content or match_parent.
Now consider a scenario where we have a searchView as a button on the right edge of the toolbar. If the title contents are more, it will go on top of the button obscuring it. There is no way of controlling this short of setting a width to the label and is something you don't want to do if you want to have a responsive design.
So, here is a solution that worked for me which is slightly different from adding a textview to the toolbar. Instead of that, add the toolbar and text view to a relative layout and ensure that the text view is on top of the toolbar. Then we can use appropriate margins and make sure the text view shows up where we want it to show up.
Make sure you set the toolbar to not show the title.
Here is the XML for this solution:
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
<android.support.v7.widget.Toolbar
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:id="#+id/activity_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:titleTextAppearance="#style/AppTheme.TitleTextView"
android:layout_marginRight="40dp"
android:layoutMode="clipBounds">
<android.support.v7.widget.SearchView
android:id="#+id/search_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:foregroundTint="#color/white" />
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="90dp"
android:text="#string/app_name"
android:textSize="#dimen/title_text_size"
android:textColor="#color/white"
android:lines="1"
android:layout_marginLeft="72dp"
android:layout_centerVertical="true" />
</RelativeLayout>
Solves the issue #ankur-chaudhary mentioned above.
Since android.support.v7.appcompat 24.2 Toolbar has method setTitleTextAppearance and you can set its font without external textview.
create new style in styles.xml
<style name="RobotoBoldTextAppearance">
<item name="android:fontFamily">#font/roboto_condensed_bold</item>
</style>
and use it
mToolbar.setTitleTextAppearance(this, R.style.RobotoBoldTextAppearance);
I spent several days searching for a universal solution. My toolbar working with android menu and nav icon.
At first, you need create custom toolbar class. This class must have calculate title centered positions (paddings):
class CenteredToolbar #JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: Toolbar(context, attrs, defStyleAttr) {
init {
addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
val titleTextView = findViewById<TextView>(R.id.centerTitle)
val x = titleTextView.x.toInt()
val x2 = x + titleTextView.width
val fullWidth = width
val fullCenter = fullWidth / 2
val offsetLeft = Math.abs(fullCenter - x)
val offsetRight = Math.abs(x2 - fullCenter)
val differOffset = Math.abs(offsetLeft - offsetRight)
if (offsetLeft > offsetRight) {
titleTextView.setPadding(differOffset, 0, 0, 0)
} else if (offsetRight > offsetLeft) {
titleTextView.setPadding(0, 0, differOffset, 0)
}
removeOnLayoutChangeListener(this)
}
})
}
override fun setTitle(resId: Int) = getTitleView().setText(resId)
override fun setTitle(title: CharSequence?) = getTitleView().setText(title)
fun getTitleView(): TextView = findViewById(R.id.centerTitle)
}
Secondly, you need create layout toolbar:
<CenteredToolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar">
<TextView
android:id="#+id/centerTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</CenteredToolbar>
That's all
Try taking Toolbar and tittle in a separate view. Take a view on right end and given them weight equal to the toolbar weight. In this way your tittle will come in center.
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:background="#color/white_color">
<LinearLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white_color">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="#color/white_color"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:layout_weight="0.2"
app:contentInsetStartWithNavigation="0dp"
app:navigationIcon="#color/greyTextColor">
</android.support.v7.widget.Toolbar>
<com.an.customfontview.CustomTextView
android:id="#+id/headingText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:gravity="center"
android:text="Heading"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/keyboard_number"
android:layout_gravity="center_horizontal|center_vertical"
app:textFontPath="fonts/regular.ttf" />
<ImageView
android:id="#+id/search_icon"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="visible"
android:layout_weight="0.2"
android:layout_gravity="center_horizontal|center_vertical"
android:src="#drawable/portfolio_icon"/>
</LinearLayout>
</android.support.design.widget.AppBarLayout>
You can insert this code in your xml file
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:textColor="#000000"
android:textSize="20dp"
android:id="#+id/toolbar_title" />
</androidx.appcompat.widget.Toolbar>
To use a custom title in your Toolbar you can add a custom title like :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="5dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:id="#+id/lnrTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/txvHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center"
android:gravity="center"
android:ellipsize="end"
android:maxLines="1"
android:text="Header"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
Java Code:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() == null)
return;
getSupportActionBar().setTitle("Title");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Use com.google.android.material.appbar.MaterialToolbar and app:titleCentered="true" tag
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:titleCentered="true" />
private void makeTitleCenter(String title, Toolbar toolbar) {
if (title != null && !TextUtils.isEmpty(title.trim())) {
final String tag = " ";
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(tag);
}
TextView titleTv = null;
View leftBtn = null;
for (int i = 0; i < toolbar.getChildCount(); i++) {
View view = toolbar.getChildAt(i);
CharSequence text = null;
if (view instanceof TextView && (text = ((TextView) view).getText()) != null && text.equals(tag)) {
titleTv = (TextView) view;
} else if (view instanceof ImageButton) {
leftBtn = view;
}
}
if (titleTv != null) {
final TextView fTitleTv = titleTv;
final View fLeftBtn = leftBtn;
fTitleTv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
fTitleTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int leftWidgetWidth = fLeftBtn != null ? fLeftBtn.getWidth() : 0;
fTitleTv.setPadding(DimenUtil.getResources().getDisplayMetrics().widthPixels / 2 - leftWidgetWidth - fTitleTv.getWidth() / 2, 0, 0, 0);
fTitleTv.requestLayout();
}
});
}
}
}
for custom font in toolbar you can override textView font in style and then every textView in your app also toolbar title font changed automatically
i tested it in android studio 3.1.3
in style do it:
<style name="defaultTextViewStyle" parent="android:Widget.TextView">
<item name="android:fontFamily">#font/your_custom_font</item>
</style>
and then in your theme use this:
<item name="android:textViewStyle">#style/defaultTextViewStyle</item>
I found another way to add custom toolbar without any adicional Java/Kotlin code.
First: create a XML with your custom toolbar layout with AppBarLayout as the parent:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
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:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<ImageView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginEnd="#dimen/magin_default"
android:src="#drawable/logo" />
</android.support.v7.widget.Toolbar>
Second: Include the toolbar in your layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue"
tools:context=".app.MainAcitivity"
tools:layout_editor_absoluteY="81dp">
<include
layout="#layout/toolbar_inicio"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Put your layout here -->
</android.support.constraint.ConstraintLayout>

Dynamically created TextView in FrameLayout has no width

I'm trying to add a TextView in code to a framelayout. This sits above an imageview in the z order of the framelayout. The ultimate aim is to allow the creation of a screenshot from the framelayout that shows the image and the text that has been overlayed on to it. I have this working when using a textview created in xml but not in the dynamic code version. The create bitmap method returns an error complaining about the width of the textbox being 0. In the code below I am trying to capture just the textview as an image to identify what the issue is, as the captured image from the framelayout did not contain the contents of the textview as expected. In doing this I was able to find the width error and I believe it is this that is the root of the problem. I have tried to set the textview's width using setWidth and also using the LayoutParams. The end result is always that the textview has no width although it can be seen on the handset clearly. I think I am missing something between the dynamic creation and the existing xml which results in the 0 width. Can anyone point me in the correct direction please?
The code is as follows
public void applyTextToImage(View view) {
// Do something in response to button
//Hide the virtual keyboard
InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//Get the text to overlay on the image
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
//Bring the overlay layout to the front
//LinearLayout overlay_layout = (LinearLayout) findViewById(R.id.image_Overlay_Layout);
//overlay_layout.bringToFront();
//Apply the new text to the text box
/* Old code to get the view that is shown in the layout
TextView text_overlay = (TextView) findViewById(R.id.image_Overlay);
text_overlay.bringToFront();
text_overlay.setText(message);
*/
//New code to create a view dynamically instead
TextView text_Overlay = new TextView(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
text_Overlay.setId(Utils.generateViewId());
}
else
{
text_Overlay.setId(TextView.generateViewId()); //static class
}
FrameLayout image_Layout = (FrameLayout) findViewById(R.id.image_Layout);
//View image_Layout = (View) findViewById(R.id.image_Layout);
//FrameLayout.LayoutParams fParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams fParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
fParams.gravity = Gravity.CENTER;
// text_Overlay.setMaxWidth(image_Layout.getWidth());
// text_Overlay.setWidth(image_Layout.getWidth());
//image_Layout.addView(text_Overlay, fParams);
image_Layout.addView(text_Overlay, fParams);
Toast.makeText(this,"TextView Width: " + text_Overlay.getWidth(),Toast.LENGTH_LONG).show();
//TODO: Something has forced the dynamic layout to not be saved in the bitmap try removing the params and set the values on the textview itself
//TODO: for some reason the width keeps coming back as 0 could be that the image_Layout is 0 too
text_Overlay.setGravity(Gravity.CENTER);
text_Overlay.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
//text_Overlay.setWidth(250dp);
text_Overlay.setTextSize(pixels);
text_Overlay.setTextColor(Color.RED);
text_Overlay.bringToFront();
text_Overlay.setText(message);
text_Overlay.setVisibility(View.VISIBLE);
//End of new dynamic code
if (folderCheck()){
try {
String filePath = getFilePath();
int myId = text_Overlay.getId();
Bitmap bitmap;
View v1 = findViewById(myId);
v1.setDrawingCacheEnabled(true);
v1.buildDrawingCache();
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
// End imported code
streamBitmapToFile(bitmap, filePath);
}
catch (Exception e)
{
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG);
Log.e("Bitmap Creation","Couldn't create bitmap error as: " + e.toString());
}
}
}
XML contents
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="false">
<!--app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_my"-->
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
android:enabled="false"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="applyTextToImage"
android:enabled="false"
android:id="#+id/overlayButton"/>
</LinearLayout>
<FrameLayout
android:id="#+id/image_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true">
<ImageView
android:id="#+id/image_View"
android:layout_width="match_parent"
android:layout_height="250dp" />
<!--<TextView
android:id="#+id/image_Overlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:textSize="25dp"
android:textColor="#ff0000"/>-->
</FrameLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/open_gallery"
android:onClick="openGallery">
</Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_image"
android:onClick="newImage">
</Button>
</LinearLayout>
</RelativeLayout>
The view has not been measured yet. Until the system does another layout pass, the view reports its width as zero.
In my opinion, you are better off leaving the TextView in the XML layout and simply making it invisible (android:visibility="invisible") until you need it, then make it visible prorammatically with setVisbility(View.VISIBLE). (Note that if you set it to be gone, it will also not be measured.)
For reference Karakuri pointed out the weaknesses and the path to follow to resolve them.
Extra code that was implemented for the listener is as follows.
IMAGE_CAPTURE_REQUESTED = true;
// New Listener
ViewTreeObserver vto = image_Layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
image_Layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
else
{
image_Layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
if (IMAGE_CAPTURE_REQUESTED) {
//int myId = text_Overlay.getId();
//Toast.makeText(MyActivity.this, "Text Overlay Width " + text_Overlay.getWidth() ,Toast.LENGTH_LONG).show();
overlayTextAndExportImage();
}
}
}); //End New Listener
The new overlayTextAndImportImage calls all the image creation routines after the layout has been redrawn.

Show activity's view overlay FrameLayout with Fragment

I have the following activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="es.xxx.xxx.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#CCFF0000"
android:id="#+id/lyNetworkError">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No hay conexión a internet"
android:textAlignment="center"/>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"/>
</RelativeLayout>
In its FrameLayout the app will load other fragments.
This is the onCreate code of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Constants.setAppContext(this);
setContentView(R.layout.activity_main);
Log.d("LoadFragment", "1 "+ loadFragment);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).commit();
}
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkStateReceiver, filter);
fragmentManager = getSupportFragmentManager();
lyNetworkError = (LinearLayout) findViewById(R.id.lyNetworkError);
}
The problem is that LinearLayout (That contains TextView) doesn't show (is posible that fragment render over LinearLayout, because if I remove getSupportFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).commit(); the LinearLayout appears)
So, how can I show the LinarLayout over fragment (loaded inside FrameLayout)?
If the LinearLayout and your Fragments are displaying in the correct location on screen when each is shown individually, then you can simply reverse the order of of the FrameLayout and LinearLayout in your XML.
The problem is that RelativeLayout allows its children to overlap. The last item in the RelativeLayout will appear "above" or "on top" of other items in the layout. Since you haven't specified any layout constraints for your views, the RelativeLayout puts them both in the default position, which is the top left corner. Since your FrameLayout is set to fill the parent view's width and height, it will overlay everything else.
If you actually want the LinearLayout to appear above the FrameLayout, then you can use RelativeLayout's positioning properties (explained very well here) to position your views.
Specifically, you would be looking for something like this:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/lyNetworkError"
android:id="#+id/container"/>
The android:layout_below attribute tells the FrameLayout that you want it to always be below the view with ID lyNetworkError (below as with text on a piece of paper, not in 3-dimensional space).

Categories