ActionBarCompat: How to hide/ remove the 'title' of the 'underlying' activity? - android

I'm using ActionBarCompat that is attached to 1 underlying activity. And there are a number of fragments that can be navigated with the navigation drawer.
And each fragment has a respective title set programatically.
Apps like the official Gmail app have a clean launcher activity, i.e the very first screen that you see for a brief moment has no icon, no title in the action bar. How can I achieve the same?
After the app is loaded with the following fragments, the ActionBar has been styled appropriately with the respective titles and icons programatically, as mentioned earlier.
I've tried the following code by putting it into the style.xml and calling it from the manifest. But this disabled Action Bar throughout the app, which I don't want.:
<style name="Theme.AppCompat.Light.NoActionBar" parent="#style/Theme.AppCompat">
<item name="android:windowNoTitle">true</item>
</style>

Just add setTitle(""); to your activity oncreate.

I think you could create your own ActionBar Layout like this:
In your BaseActivity (you have one, right?) do something like this:
public class BaseActivity extends ActionBarActivity {
private TextView mActionBarTextView;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View actionBarView = inflator.inflate(R.layout.ab_custom_view, null);
mActionBarTextView = (TextView) actionBarView.findViewById(R.id.title);
mActionBarTextView.requestFocus();
this.getSupportActionBar().setCustomView(actionBarView);
setTitle(Constants.EMPTY_STRING);
}
}
ab_custom_view.xml would look like (set your own TextView preferences, this is just an untested example):
<?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="#android:color/transparent">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:textColor="#color/white"
android:textSize="18sp"
android:maxLines="1"
android:ellipsize="marquee"
android:focusable="true"
android:singleLine="true"
android:focusableInTouchMode="true" />
</RelativeLayout>
Back in your BaseActivity, add the folowing convenience methods:
#Override
public void setTitle(final CharSequence title) {
if (mActionBarTextView != null) {
if (title != null) {
mActionBarTextView.setText(title);
} else {
mActionBarTextView.setText(null);
}
requestTitleFocus();
}
}
#Override
public void setTitle(final int titleId) {
if (mActionBarTextView != null) {
if (titleId > 0) {
mActionBarTextView.setText(getString(titleId));
} else {
mActionBarTextView.setText(getString(R.string.some_default_string);
}
requestTitleFocus();
}
}
public void requestTitleFocus() {
if (mActionBarTextView != null) {
mActionBarTextView.requestFocus();
}
}
Finally, in your activities (that inherit from BaseActivity), if you need to set a different than empty title:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Your Title");
}
(I assume you store your mostly used Strings in a static final field for convenience and efficiency…)
public final class Constants {
public static final String EMPTY_STRING = "";
}
This should do the trick.
The perk you gain is that you could use a custom Font in the ActionBar (to match your App's font if you were using a custom one) because you have full control (and a reference) to your ActionBar's textview. ;)

Try using style for your activity in manifest file. Remember, in your onCreate() method you must call setStyle() or requestWindowFeature() before setContentView() when you want your action bar or app style back.
<style name="MyApp.Fullscreen" parent="android:Theme.Black.NoTitleBar">
<item name="android:windowBackground">#color/app_background</item>
</style>

Related

how to reuse custom actionbar to all the activities in an application?

I have created a custom action bar which works fine on my starting activity but gives an error when I call the method from other activities in the same application.
This is the code I am using to set the ActionBar in my first activity
firstAct.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBarSetup(this);
}
void actionBarSetup(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar ab = getActionBar();
ab.setDisplayShowCustomEnabled(true);
ab.setDisplayShowTitleEnabled(false);
ab.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
LayoutInflater inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.actionbar_layout, null);
//assign the view to the actionbar
ab.setCustomView(v);
}
}
**secondAct.java**
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_pg);
(new firstAct()).actionBarSetup(secondAct.this);
}
I get NullPointerException when i call actionBarSetup() from secondAct.java
on line ActionBar ab = getActionBar().
Is it that getActionBar() cannot be called directly from other activities besides the main activity ie. firstAct.
How to call it from other Activities then?
You don't create new activities by calling their constructor. You have the system create and open them for you. I'm talking about the line
(new firstAct()).actionBarSetup(secondAct.this)
What are you trying to do here?
You probably want to make the actionBarSetup method accessible for all classes and not just instances of firstAct. Then declare it like this (maybe move it to a utility class?):
public static void actionBarSetup(Activity activity) {
ActionBar ab = activity.getActionBar(); // you need activity, not just context
// ...
}
Then call it from other classes like this:
firstAct.actionBarSetup(this);
Making a method static detaches it from an instances resources. You were taking in second activity (context parameter) but asking for an action bar from instance of the first activity (essentially this.getActionBar()) which was not setup by system (because you misused constructor).
Note: Please use PascalCase notation for class names (capital first letter).
EDIT
Warning: Your action bar may have different styling from your activity (e.g. black toolbar and white activity). In that case using the activity's inflater to inflate contents of the action bar will produce undesired results (inverted text color mainly). The following line is safer. But it's available no sooner than API 14.
LayoutInflater inflator = LayoutInflater.from(ab.getThemedContext());
You need create BaseActivity like
public class BaseActivity extends Activity {
public void actionBarSetup(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar ab = getActionBar();
ab.setDisplayShowCustomEnabled(true);
ab.setDisplayShowTitleEnabled(false);
ab.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
LayoutInflater inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.actionbar_layout, null);
//assign the view to the actionbar
ab.setCustomView(v);
}
}
then you need firstAct and secondAct extend BaseActivity then in onCreate method call actionBarSetup()
This may help
private void showCustoNavBar(){
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.new_gradient));
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
View customNav = LayoutInflater.from(this).inflate(R.layout.actioncustomview, null);
getSupportActionBar().setCustomView(customNav);
}

Actionbar, Toolbar, activity inheritance

My activities extend from a generic base activity, where I declare and initialize public variables like context of type Context, activity of type Activity and mActionBar of type ActionBar.
So this avoids redundant initialization code in all my app's activities.
But with the advent of Toolbar, I am a little confused on how to do this. Toolbar is not like ActionBar and replaces it, but also extends it.
The ActionBar is a view object that is always available for retrieval, by ActionBar activity, and it sits above the views that are created. This is not declared in layout XML anywhere.
But Toolbar is declared only in layout XML, so I have to include it in each and every layout I create, or else I will not be able to access the Toolbar object.
I typically use setContentView(R.layout.mylayout) in the onCreate method of each individual activity. And then I have to initialize my Toolbar object after that using findViewById. Therefore I can't put this code in my BaseActivity's onCreate function because the setContentView wouldn't have been initialized yet.
Even if I created Toolbar programmatically with it's constructor, and attempted to add the view to the top of the hierarchy, I would still have to do this on a layout by layout, and activity by activity basis, because some layouts are RelativeLayout's as the root object, and others are different. So these will still have separate code considerations.
The reason I am curious about a good way for my activities to inherit Toolbar, is because it is a complete nightmare for Google to suddenly require Android 4.0-4.4 devices to use the v7 compatibility pack, replace the actionbar completely with the Toolbar object, use v4 compatibility pack fragments instead of native ones, all to use the latest design paradigms.
this is my implementation. Hope it helps someone.
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>

Set a title in Toolbar from fragment in Android

I have been using the latest Toolbar from AppCompatv7 lib.I have placed a textview in the ToolBar ViewGroup And I want to set a title into this Textview from the fragment in my activity.In case of a custom action bar ((ActionBarActivity)getActivity).setcustomView(..) would have done the job.But due to use of this ToolBar I am not able to use that.Also I have implemented a method in my BaseActivity that is inherited by all Activities.This BaseActivity contains my method to initialize a sliding drawer to the left.I have to initialize the initDrawerLayout() method in activity else the drawer would not be initialized.And if I initialize it in fragment its giving me all empty results,neither the toggle button for drawer and nor is the custom title getting set.
This is my initDrawer code..
public void initDrawerLayout(String toolbar_text) {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelative = (RelativeLayout) findViewById(R.id.drawer_relative);
if (mDrawerLayout != null) {
findViewById(R.id.drawer_btn_a).setOnClickListener(this);
findViewById(R.id.drawer_btn_b).setOnClickListener(this);
findViewById(R.id.drawer_btn_c).setOnClickListener(this);
findViewById(R.id.drawer_btn_d).setOnClickListener(this);
findViewById(R.id.drawer_btn_e).setOnClickListener(this);
findViewById(R.id.drawer_btn_f).setOnClickListener(this);
findViewById(R.id.drawer_btn_g).setOnClickListener(this);
findViewById(R.id.drawer_btn_h).setOnClickListener(this);
findViewById(R.id.drawer_btn_i).setOnClickListener(this);
findViewById(R.id.drawer_btn_j).setOnClickListener(this);
findViewById(R.id.drawer_btn_k).setOnClickListener(this);
findViewById(R.id.drawer_btn_l).setOnClickListener(this);
findViewById(R.id.my_layout).setOnClickListener(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setBackground(getResources().getDrawable(R.drawable.icn_actionbar_background));
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText(toolbar_text);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
toolbar.setNavigationIcon(R.drawable.ic_drawer);
mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar,
R.string.drawer_open, R.string.drawer_close
);
mDrawerLayout.setDrawerListener(mDrawerToggle);
toolbar.setNavigationOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
} else {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
}
});
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mDrawerLayout.setScrimColor(getResources().getColor(
android.R.color.transparent));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
}
And this my code in the fragment..
((FirstActivity) getActivity()).initDrawerLayout(mFirst.name);
where mFirst is a object of class Person
and the toolbar code..
<android.support.v7.widget.Toolbar
android:id="#+id/my_awesome_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Toolbar Title"
android:textColor="#color/action_text-color"
android:textSize="18sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
Please help guys..
I do this like this:
from the fragment call
getActivity().setTitle("your title");
But where you call it is important, because if each Fragment has it's own title, then one may override the other accidentally, which may be prevented like:
#Override
public void onResume() {
super.onResume();
Activity activity = getActivity();
if (activity != null) {
activity.setTitle(getString(R.string.my_title));
}
}
For example, two Fragments of the same Pager can not be in resume-state at the same time.
Also you can "cast", to call any function of your parent Activity like this:
YourActivity mYourActiviy = (YourActivity) getActivity();
mYourActivity.yourActivityFunction(yourParameters);
In Kotlin.
In fragment:
(activity as YourActivity).supportActionBar?.title = getString(R.string.your_title)
In activity:
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
If you have setSupportActionBar in Your Activity then you can easily change the toolbar title from your fragment
((YourActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
To allow a Fragment to communicate up to its Activity (to set your Toolbar Title), you can define an interface in the Fragment class and implement it within the Activity as described here: Communicating with Other Fragments.
The answer is writen below in the oncreateview method of fragments.
getActivity().setTitle("your name");
You can create Interface inside the Fragment. check below:-
public class MyFragment extends Fragment {
OnMyFragmentListener mListener;
// Where is this method called??
public void setOnMyFragmentListener(OnMyFragmentListener listener) {
this.mListener = listener;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMyFragmentListener) {
mListener = (OnMyFragmentListener) context;
mListener.onChangeToolbarTitle("My Fragment"); // Call this in `onResume()`
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onResume(){
super.onResume();
mListener.onChangeToolbarTitle("My Fragment");
}
// This interface can be implemented by the Activity, parent Fragment,
// or a separate test implementation.
public interface OnMyFragmentListener {
public void onChangeToolbarTitle(String title);
}
}
In Activity:-
public class MyActivity extends AppCompatActivity implements MyFragment.OnMyFragmentListener {
#Override
public void onChangeToolbarTitle(String title){
toolbar.setTitle(title);
}
}
This works for me. :)
This has worked for me, in Kotlin. Put this in your fragment class:
if (activity != null) {
(activity as MainActivity).supportActionBar?.title = getString(R.string.action_history)
}
If somebody struggles with this problem, this may be useful.
Basically you have 4 options, how to handle that:
use an interface in order to communicate with your activity, or any other convenient method, like an event bus.
you call getActivity().setTitle("Title"), but in this case you need to attach your Toolbar to the ActionBar by calling the setSupportActionBar() in your activity.
You can have a public instance of your Toolbar and access that instance from the fragment.
Finally, if you need the instance of your Toolbar(you may want to do something else with), you can simply get it this way:
Toolbar bar=Toolbar.class.cast(getActivity().findViewById(R.id.toolbar));
Well, the last option would solve the problem only if the Toolbar hasn't been passed to the setSupportActionBar method.
If it has been, then you need to call this method in your activity:
supportActionBar.setDisplayShowTitleEnabled(false),
which will solve the problem.
However, I would suggest to use ButterKnife which will make it a little bit cleaner, here an example:
Toolbar actionBar=findById(getActivity(),R.id.actionBar);
actionBar.setTitle("Title");
In Kotlin, I use
fun onAttach(...){
..
activity?.title = "My Title"
}
This work for me :
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.id_toolbar);
toolbar.setTitle("New Title");
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
FragmentManager.BackStackEntry lastBackStackEntry=null;
int lastBackStackEntryCount = getSupportFragmentManager().getBackStackEntryCount() - 1;
if(lastBackStackEntryCount >= 0 )
{
lastBackStackEntry = getSupportFragmentManager().getBackStackEntryAt(lastBackStackEntryCount);
}
Toast.makeText(MainActivity.this, ""+lastBackStackEntryCount, Toast.LENGTH_SHORT).show();
if(lastBackStackEntryCount == -1)
{
toolbar.setTitle("");
toolbar.setLogo(R.drawable.header_logo);
}
else
{
toolbar.setTitle(lastBackStackEntry.getName());
}
}
});
For me the problem was that for some reason the label was overwritten. I had to change it back to the string resource, in
navigation.xml
inside the fragment tag;
android:label="#string/android_trivia"
You can change the title of your toolbar on the event OnAttach, something like this
var toolbar = activity.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.Title = "New Title";
In your Activity declare the toolbar as public.
public class YourActivity : Activity
{
public Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = .... // initilize your toolbar
}
}
Then, from your fragment
((YourActivity) getActivity()).toolbar.Title = "Your Title";
If you are using a custom toolbar, this will help you:
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("Feedback");
You need to set the title in activity commiting the fragment and return the fragment
getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment, mainFragment).commit();
toolbar.setTitle("ShivShambhu");
return contentFragment;
This works for me.
xml
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_detail"
android:layout_width="match_parent"
android:layout_height="55dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"
android:background="#color/tool_bar_color">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#fff"
android:textSize="16sp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
Find TextView Id from toolbar
if you are using Activity
TextView mTitle = findViewById(R.id.toolbar_title);
mTitle.setText("set your title");
if you are using Fragment
TextView mTitle = view.findViewById(R.id.toolbar_title);
mTitle.setText("set your title");
Here's one simple solution.
In your activity that extends AppCompatActivity, you can do this:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
The inside its fragment, you can do this:
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title);

Is it possible to display a DialogFragment in a master-detail arragement without a new activity?

I'm looking for a way to display a DialogFragment in single-pane mode without creating a new activity.
I originally set up a DialogFragment as a popup dialog in my Android app, with the intent to eventually pursue the master-detail pattern for larger devices.
However, now that I'm looking to finally implement the master-detail setup I'm running into all sorts of UI complications. Basically, I'd like to have something like a 'contextual action mode' update to the action bar. That requires some planning in two-pane mode, but it doesn't work at all with a popup dialog (unless I'm missing some way to show the action bar and the popup dialog).
I'd rather not create a new activity to house the detail DialogFragment on non-tablet/large devices, since there is a lot of DB-related code in the existing activity. However, I have trouble just doing FragmentTransaction.replace because the main view is based on a modified FragmentTabsPager from the compatibility lib v4 demo. I don't have a fragment to replace, unless I wrap the entire pager in a fragment - and I'm worried that nesting fragments is a hack that will complicate, rather simplify things in the long run. Am I wrong?
I'm also using ActionBarCompat, which complicates things as there are some UI options that aren't ported. I'd consider going API 11+ if it meant finding a clean solution to this.
BTW I'm starting to look at Commonsware's master-detail library, but it's a bit of code to grok and ingest, and I think it would require a few possibly big changes to make my code compatible.
Any suggestions or comments? I think I'm too close to this one to see how to simplify it...
(1) You should definitely not have to create an entire new Activity whose sole purpose is to house a new DialogFragment. If you are going to create a new activity at all, you might as well just give it a dialog-theme and display that as your dialog instead... that would eliminate the need to show a DialogFragment entirely.
(2) Your question is a bit too general for me to give a confident answer... you mention "contextual action mode", "dialog fragment", "fragment tabs pager", "nested fragments", etc. and I'm not sure how it all fits together or what specifically you are trying to achieve. What I do know is that no matter the configuration, the host activity should always be the one in charge of performing fragment transactions (such as showing a DialogFragment) as this will significantly reduce code complexity (especially when the number of fragments displayed on the screen varies depending on the screen size). Do your fragments communicate with the activity via activity callback methods (as described here and here)? Where in your code do you show the DialogFragment: in your activity or in one of the master/detail fragments?
Try this:
This is the XML of the layout of your Activity.
What you need to do is enclose all your activity content in a layout (like i have done here in id = all_activity_content_id).
Now put two more views in the activity:- A RelativeLayout for your dialog and a View for making the background translucent.
Note: Make sure the root layout of your activity is a RelativeLayout
<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="in.curium.testandroid.MainActivity" >
<!-- all your activity's existing code goes here -->
<RelativeLayout
android:id="#+id/all_activity_content_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/holo_red_light" >
<ToggleButton
android:id="#+id/toggle_dialog_box_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:padding="10dp"
android:textOff="#string/show_dialog"
android:textOn="#string/hide_dialog" />
</RelativeLayout>
<!-- translucent black background behind the dialog -->
<View
android:id="#+id/black_layer_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:alpha="0.6"
android:background="#android:color/black"
android:visibility="gone" />
<!-- your dialog layout -->
<RelativeLayout
android:id="#+id/dialog_id"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#00BFFF"
android:visibility="gone" >
<TextView
android:id="#+id/dialog_title_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:text="#string/dialog_title"
android:textColor="#android:color/white" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/dialog_title_id"
android:text="#string/dialog_description" />
</RelativeLayout>
In your activity class add two methods to show and hide the dialog layout.
Override the back button to dismiss the dialog when visible otherwise call super.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggle_dialog_box_id);
toggleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View toggleB) {
boolean isOn = ((ToggleButton) toggleB).isChecked();
if (isOn) {
showDialog();
} else {
hideDialog();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void showDialog() {
View opaqueBackground = findViewById(R.id.black_layer_id);
RelativeLayout dialog = (RelativeLayout) findViewById(R.id.dialog_id);
opaqueBackground.setVisibility(View.VISIBLE);
dialog.setVisibility(View.VISIBLE);
}
private void hideDialog() {
View opaqueBackground = findViewById(R.id.black_layer_id);
RelativeLayout dialog = (RelativeLayout) findViewById(R.id.dialog_id);
opaqueBackground.setVisibility(View.GONE);
dialog.setVisibility(View.GONE);
}
#Override
public void onBackPressed() {
ToggleButton toggleB = (ToggleButton) findViewById(R.id.toggle_dialog_box_id);
boolean isOn = toggleB.isChecked();
if (isOn) {
toggleB.setChecked(false);
hideDialog();
} else {
super.onBackPressed();
}
}}
Now any code that you want to put in the dialog will have access to the database adapter that you have in the activity.
Positioning the dialog in the center of your detail fragment will be a bit tricky.
Hope this helps.
Source Code: https://github.com/testv200/DialogInsideAcitvity
It's not possible Because you are using Activity
If you extends FragmentActivity than it's only possible because if you want to show DialogFragment than it's required FragmentManager reference it's not possible in normal Activity. It's provide only inside FragmentActivity or above API level 13
This is my DialogFragment class
public class DetailedFragment extends DialogFragment {
private static final String ARG_SHOW_AS_DIALOG = "DetailedFragment.ARG_SHOW_AS_DIALOG";
public static DetailedFragment newInstance(boolean showAsDialog) {
DetailedFragment fragment = new DetailedFragment();
Bundle args = new Bundle();
args.putBoolean(ARG_SHOW_AS_DIALOG, showAsDialog);
fragment.setArguments(args);
return fragment;
}
public static DetailedFragment newInstance() {
return newInstance(true);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
setShowsDialog(args.getBoolean(ARG_SHOW_AS_DIALOG, true));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.detailed_fragment, container, false);
}
}
This is my ActionBarActivity Class
This is the code for showing Dialog inside ActionBarActivity class.I think Please check your import statements
public class DetailedActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailed_activity);
if (savedInstanceState == null) {
DetailedFragment fragment = DetailedFragment.newInstance(false);
getSupportFragmentManager().beginTransaction().add(R.id.root_layout_details, fragment, "Some_tag").commit();
}
}
}

custom title bar is not working android

Hi i have set up a custom title bar but the app crashes and i don't get any error log in LogCat, i'm going crazy. Here's is some code, can you experts see what's wrong?
boolean isCustomTitleSupported;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isCustomTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.about);
customizeTitleBar("My Title");
public void customizeTitleBar(String title){
if(isCustomTitleSupported){
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitlebar);
TextView customTitleText = (TextView)findViewById(R.id.customtitle);
customTitleText.setText(title);
customTitleText.setTextColor(Color.WHITE);
}
}
customtitlebar.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/customtitle"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textStyle="bold"
android:padding="3px"
/>
</LinearLayout>
some help will be appreciated
Thanks!!
EDIT: i noticed that i wasn't extending Activity but BaseActivity a superclass i created to have the menu available in all of my activities. So i changed back to extend Activity and it's working but this is a problem because i need menus too. Is there any tricks so i could keep extending BaseActivity and even get the title bar to work?
Have you tried setting the title bar before setting the content view ?
customizeTitleBar("My Title");
setContentView(R.layout.about);
You are trying to extract the customtitle TextView from the wrong layout. When you use findViewById it defaults to your current activity's layout, which you set to R.layout.about. You need to use a layout inflater to inflate R.layout.customtitlebar and then call findViewById from that (since the customtitle view is in the customtitlebar layout).
Something like this:
View view = getLayoutInflater().inflate(R.layout.customtitlebar);
TextView customTitleText = (TextView)view.findViewById(R.id.customtitle);
It seems to be half working now, but no title is being set, i mean that i get an empty title bar here's is what i got:
About.java
public class About extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
customizeTitleBar("APP TITLE");
setContentView(R.layout.about);
}
}
BaseActivity.java
public class BaseActivity extends Activity {
boolean isCustomTitleSupported;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isCustomTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
customizeTitleBar("MY TITLE");
}
public void customizeTitleBar(String title){
if(isCustomTitleSupported){
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitlebar);
View view = getLayoutInflater().inflate(R.layout.customtitlebar, null);
TextView customTitleText = (TextView)view.findViewById(R.id.customtitle);
customTitleText.setText(title);
customTitleText.setTextColor(Color.WHITE);
}
}
}
Request the windowfeature --> setContentView --> customize Title
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Boolean customTitle = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.listviewoffers);
customTitle(R.string.dashboard_offers, 0, R.id.listViewTitle, customTitle);
This are the first lines of my onCreate.
The customTitle() is in my superclass.
public void customTitle(int middle, int right, int altTitle, Boolean customTitle) {
if (customTitle) {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebarlayout);
TextView titleMiddle = (TextView) findViewById(R.id.middleTitleBar);
titleMiddle.setText(getResources().getString(middle));
TextView titleRight = (TextView) findViewById(R.id.rightTitleBar);
if (right != 0) {
titleRight.setText(getResources().getString(right));
} else {
titleRight.setVisibility(View.GONE);
}
TextView title = (TextView) findViewById(altTitle);
title.setVisibility(View.GONE);
} else {
setTitle(getResources().getString(R.string.dashboard_offers));
}
}
It is a layout with 2 textviews, one in the middle, one in the right. The right can be set as gone.

Categories

Resources