I am trying to set the toolbar for a class that extends AppCompatActivity programmatically, but the activity does not have a toolbar when it is run. Every tutorial I have been able to find on using toolbars have the toolbar being created and added in XML, but I am looking for a better way to add the toolbar to all my activities, so I am trying to do it programmatically. However, the toolbar is either not visible or not added when I run, and I cannot find the problem. This is my code:
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = new Toolbar(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, R.attr.actionBarSize);
toolbar.setLayoutParams(layoutParams);
toolbar.setPopupTheme(R.style.AppTheme);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
toolbar.setTitle("This is the title");
toolbar.setVisibility(View.VISIBLE);
setSupportActionBar(toolbar);
}
}
And this is my XML file activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</LinearLayout>
I cannot figure out what is wrong with my toolbar. Thank you in advance for any help.
Add Toolbar to your Activity layout using YOUR_LAYOUT.addView(toolbar, 0):
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = new Toolbar(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 168);
toolbar.setLayoutParams(layoutParams);
toolbar.setPopupTheme(R.style.AppTheme);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
toolbar.setTitle("This is the title");
toolbar.setVisibility(View.VISIBLE);
// Assuming in activity_main, you are using LinearLayout as root
LinearLayout ll = (LinearLayout) findViewById(R.id.your_linear_layout);
ll.addView(toolbar, 0);
setSupportActionBar(toolbar);
}
}
Use MainActivity theme AppTheme.NoActionBar to avoid RuntimeException:
This Activity already has an action bar supplied by the window decor.
Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set
windowActionBar to false in your theme to use a Toolbar instead.
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
OUTPUT:
Hope this will help~
Related
I m using navigation drawer and want to put a launcher icon to the right of navigation drawer icon and put a title on right of launcher icon in ActionBar. I m trying this but didn't get the expected result.
Image here :
I m using
actionbar.setLogo(imageId); //to set the launchericon
actionbar.setTitle("home"); //to set the title
but the problem is, didn't able to set the launcher icon position in ActionBar.
please help me out.
Thanks in advance.
Use below code to set logo and title on your ActionBar :
RESULT / OUTPUT :
CODE:
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setTitle("Home");
FULL CODE :
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Here is the code
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setTitle("Home");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
I hope you mean to say that your toolbar logo is not getting displayed for a custom toolbar. A possible workaround for that would be to an <ImageView> to your custom toolbar itself and set the image.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/my_custom_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_custom"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Title"
android:id="#+id/custom_title"
android:layout_toRightOf="#id/menu_icon"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
Note that you could also add the android:centerHorizontal="true" to the textview if you want the title to be in center. Next declare the toolbar and call the textview in the required file by the id
TextView customTitle = (TextView) findViewById(R.id.custom_title);
customTitle.setText("My Custom Title");
Instead of using the getSupportActionBar().setLogo(R.mipmap.ic_launcher); we have defined it in the xml. Now use this code in the java.
ImageView cumstomIcon = (ImageView) findViewById(R.id.my_custom_icon);
customIcon.setImageResource(R.drawable.some_image);
You can also directly set the image in the xml but if you need to keep diff. images for various activities, then set the image programmatically..
Any doubts drop a comment!
Programmatically setting my FloatingActionButton's backgroundTint via setBackgroundTintList method does not work, but setting it via XML app:backgroundTint tag does work - why is that?
The fab_background_color.xml color list state is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:color="#654321"/>
<item android:color="#123456"/>
</selector>
My activity layout is:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.FloatingActionButton
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</android.support.design.widget.CoordinatorLayout>
and activity code:
public class SampleActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_position_sample);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.test);
// Uncomment to test - this does NOT work however.
//fab.setBackgroundTintList(getResources().getColorStateList(R.color.fab_background_color));
fab.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v)
{
if (fab.isSelected())
fab.setSelected(false);
else
fab.setSelected(true);
}
});
}
}
If I add:
fab.setBackgroundTintList(getResources().getColorStateList(R.color.fab_background_color));
or:
fab.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.fab_background_color));
To the activity code before setting up the click listener, nothing happens.
If I add:
app:backgroundTint="#color/fab_background_color"
To the activity layout code for the FloatingActionButton, I get the expected behavior.
Any thoughts? Am I doing something wrong?
use this:
fab.setBackgroundTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.purple_200));
Since setBackgroundTintList is only supported in API 21+ you can use ViewCompat.
ViewCompat.setBackgroundTintList(
fab,
ContextCompat.getColorStateList(
getApplicationContext(),
R.color.purple_200
)
);
This issue has been resolved as of Android Support Library 25.1.0
See: https://code.google.com/p/android/issues/detail?id=227428
My Custom ToolBar is not showing up the title
image:
My Main:
Toolbar toolbar_exit = (Toolbar) findViewById(R.id.toolbar_simple_exit); // Attaching the layout to the toolbar object
setSupportActionBar(toolbar_exit); // Setting toolbar as the ActionBar with setSupportActionBar() call
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("Help");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
my Manifest:
<activity
android:name=".Activities.HelpActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="Work Stupid Title"
android:theme="#style/NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".Activities.AtividadePrincipal" />
</activity>
why its not showing? ive tried this.setTitle and other, nothing worked
Please be specific when you ask questions by posting your customized layout files and related java code.
Set your style theme's parent of type .NoActionBar? and set the following attributes.
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="windowActionModeOverlay">true</item>
You should set a custom layout for the action bar, then set text for the textview on the custom layout of the action actionbar. This is my code:
private void setCustomActionbarView() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setContentInsetsAbsolute(0, 0);
setSupportActionBar(toolbar);
mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setDisplayShowCustomEnabled(true);
// kiem tra lai ham nay
mActionBar.setDisplayHomeAsUpEnabled(true);
LayoutInflater mInflater = LayoutInflater.from(this);
View mActionBarView = mInflater
.inflate(R.layout.custom_actionbar, null);
mActionBar.setCustomView(mActionBarView);
}
and my custom layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.orangestudio.mpromotion"
android:id="#+id/linBang"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textAcb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/home_khuyen_mai"
android:textColor="#color/acb_text_color"
app:font="#string/font_bold" />
Set the actionbar title:
View actionbarView = getSupportActionBar().getCustomView();
TextView text =(TextView) actionbarView.findViewById(R.id.textAcb);
text.setText("YOUR TITLE");
I am try to custom the ActionBar by using xml in Android.
The actionbat.xml is like the following:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bar_background" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/bar_icon"/>
</RelativeLayout >
And I using the following code to set ActionBar in Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.function_list, container, false) ;
ActionBar bar = getActivity().getActionBar();
bar.setCustomView(R.layout.actionbar);
But the ActionBar didn't change anything , did I missing something ?
---------------------------EDIT------------------------------
I have try getSupportActionBar, but it show The method getSupportActionBar() is undefined for the type Activity.
Thanks in advance.
You can try like this
View view=getLayoutInflater().inflate(R.layout.vw_custom_action_bar, null);
ActionBar actionBar=getActivity().getSuppotedActionBar() // for ActionBarActivity
//ActionBar actionBar=getActivity().getActionBar() // for Fragmentactivity
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setHomeButtonEnabled(false);
actionBar.setCustomView(view);
Try this..
View view = inflater.inflate(R.layout.function_list, container, false) ;
ActionBar bar = getActivity().getSuppotedActionBar();
bar.setCustomView(R.layout.actionbar);
I think you are not able to access the activity in onCreateView(). Try this in onActivityCreated().
For this you should have an activity that extends ActionbarActivity and that activity have fragments.inside your activity do below code -
actionbar = getSupportActionBar();
mFragmentManager = getSupportFragmentManager();
actionbar.setDisplayShowCustomEnabled(true);
actionbar.setDisplayUseLogoEnabled(false);
actionbar.setDisplayShowHomeEnabled(false);
actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionbar.setCustomView(getLayoutInflater().inflate(R.layout.actionbar, null),
new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER
)
);
mImageView = (ImageView) actionbar.getCustomView().findViewById(R.id.image_view);
hope this answer helpfull for you.
But wait.
what you are asking to say is very bad.
The fragment should not know it's activity like this.
you should do something like that:
Fragment:
void onAttach(Activity activity){
parent = (MyFragmentListener) activity;
}
void onActivityCreated(Bundle b){
parent.askToDoSomethingSpecial();
}
Activity implements MyFragmentListener:
void askToDoSomethingSpecial(){
getActionBar.setCustomView(R.layout.actionbar);
// or getSupportedActionBar.setCustomView(R.layout.actionbar);
}
In order to set custom Actionbar in Android, All you need to do is:-
getSupportActionBar().setDisplayShowCustomEnabled(true);
LayoutInflater inf = LayoutInflater.from(this);
View v = inf.inflate(R.layout.custom_tv, null); //**custom_tv is layout for actionbar**
((TextView)v.findViewById(R.id.title)).setText(title);
getSupportActionBar().setCustomView(v);
/*
* Use this if you are working with fragment
* getActivity().getSupportActionBar().setDisplayShowCustomEnabled(true);
*/
Thats it. Hope this helps.
I have searched and searched to find an answer to how to add a vertical (or horizontal) scrollbar to a TextView without having to use the XML just to add the line: android:scrollbars="vertical".
There has to be a way to do this programmatically that doesn't require sticking this within another ScrollView.
I've just found out how and because I am way to excited about this and want to help anyone else who is stuck with the same question, here it is:
Rusian Yanchyshyn, posted the key in his answer at Android: Enable Scrollbars on Canvas-Based View
With the help of an anonmous class & an initializer block we can now do the following:
TextView textViewWithScrollBars = new TextView(context)
{
{
setVerticalScrollBarEnabled(true);
setMovementMethod(ScrollingMovementMethod.getInstance());
setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
// Force scrollbars to be displayed.
TypedArray a = this.getContext().getTheme().obtainStyledAttributes(new int[0]);
initializeScrollbars(a);
a.recycle();
}
}
// try this
activity_main.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">
</LinearLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = new TextView(this);
textView.setText("demotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotext");
textView.setVerticalScrollBarEnabled(true);
textView.setLines(3);
textView.setMovementMethod(new ScrollingMovementMethod());
addContentView(textView,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
Show only when scroll
Xml (in textView element):
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="vertical"
OnCreate:
textView.movementMethod = ScrollingMovementMethod()
first - Make a style.xml
<style name="VerticalScrollableTextView">
<item name="android:scrollbars">vertical</item>
<item name="android:scrollbarFadeDuration">0</item>
</style>
second - use ContextWrapper
val textView = TextView(
ContextThemeWrapper(context, R.style.VerticalScrollableTextView)
)
textView.movementMethod = ScrollingMovementMethod.getInstance()
That's All!