How to implement MiniDrawer using mikepenz/MaterialDrawer - android

I am trying to implement MiniDrawer using mikepenz/MaterialDrawer github library. I could get some result as below picture. but the top part of MiniDrawer is hidden by Toolbar. How can i solve this problem.
This is MainActivity.Java
public class MainActivity extends AppCompatActivity {
private Drawer result = null;
private MiniDrawer miniResult = null;
private Crossfader crossFader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withTranslucentNavigationBar(false)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.drawer_item_compact_header).withIcon(GoogleMaterial.Icon.gmd_wb_sunny).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.drawer_item_action_bar_drawer).withIcon(FontAwesome.Icon.faw_home).withBadge("22").withBadgeStyle(new BadgeStyle(Color.RED, Color.RED)).withIdentifier(2).withSelectable(false),
new PrimaryDrawerItem().withName(R.string.drawer_item_multi_drawer).withIcon(FontAwesome.Icon.faw_gamepad).withIdentifier(3),
new PrimaryDrawerItem().withName(R.string.drawer_item_non_translucent_status_drawer).withIcon(FontAwesome.Icon.faw_eye).withIdentifier(4),
new PrimaryDrawerItem().withDescription("A more complex sample").withName(R.string.drawer_item_advanced_drawer).withIcon(GoogleMaterial.Icon.gmd_adb).withIdentifier(5),
new SectionDrawerItem().withName(R.string.drawer_item_section_header),
new SecondaryDrawerItem().withName(R.string.drawer_item_open_source).withIcon(FontAwesome.Icon.faw_github),
new SecondaryDrawerItem().withName(R.string.drawer_item_contact).withIcon(GoogleMaterial.Icon.gmd_format_color_fill).withTag("Bullhorn"),
new DividerDrawerItem(),
new SwitchDrawerItem().withName("Switch").withIcon(Octicons.Icon.oct_tools).withChecked(true).withOnCheckedChangeListener(onCheckedChangeListener),
new ToggleDrawerItem().withName("Toggle").withIcon(Octicons.Icon.oct_tools).withChecked(true).withOnCheckedChangeListener(onCheckedChangeListener)
) // add the items we want to use with our Drawer
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem instanceof Nameable) {
Toast.makeText(MainActivity.this, ((Nameable) drawerItem).getName().getText(MainActivity.this), Toast.LENGTH_SHORT).show();
}
return false;
}
})
.withGenerateMiniDrawer(true)
.withSavedInstance(savedInstanceState)
.buildView();
miniResult = result.getMiniDrawer();
int firstWidth = (int) UIUtils.convertDpToPixel(300, this);
int secondWidth = (int) UIUtils.convertDpToPixel(72, this);
crossFader = new Crossfader()
.withContent(findViewById(R.id.main_content))
.withFirst(result.getSlider(), firstWidth)
.withSecond(miniResult.build(this), secondWidth)
.withSavedInstance(savedInstanceState)
.build();
miniResult.withCrossFader(new CrossfadeWrapper(crossFader));
//define a shadow (this is only for normal LTR layouts if you have a RTL app you need to define the other one
crossFader.getCrossFadeSlidingPaneLayout().setShadowResourceLeft(R.drawable.material_drawer_shadow_left);
}
private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(IDrawerItem drawerItem, CompoundButton buttonView, boolean isChecked) {
if (drawerItem instanceof Nameable) {
Log.i("material-drawer", "DrawerItem: " + ((Nameable) drawerItem).getName() + " - toggleChecked: " + isChecked);
} else {
Log.i("material-drawer", "toggleChecked: " + isChecked);
}
}
};
#Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
outState = result.saveInstanceState(outState);
//add the values which need to be saved from the crossFader to the bundle
outState = crossFader.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (crossFader != null && crossFader.isCrossFaded()) {
crossFader.crossFade();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.findItem(R.id.menu_1)
.setIcon(new IconicsDrawable(this, FontAwesome.Icon.faw_repeat)
.color(Color.WHITE).actionBar());
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_1:
crossFader.crossFade();
return true;
case R.id.act_settings:
return true;
default:
}
return super.onOptionsItemSelected(item);
}
}
This is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.sldroids.minidrawer_v3.MainActivity">
<android.support.design.widget.AppBarLayout
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" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>

#sendtodilanka the problem is that you add the Crosssfader as the parent of the main_content view, which is a direct child of your CoordinatorLayout.
As the CoordinatorLayout is similar to the FrameLayout and does overlap views your Crossfader will simply be displayed below the AppBarLayout which you have defined to be over the main_content.
To get the Crossfader below the Toolbar you should add a new View around your main_content, let's choose a FrameLayout which has the attribute (don't forget to define the appBarLayout id to your AppBarLayout)
xml
app:layout_behavior="#string/appbar_scrolling_view_behavior"
After this the Crossfader will get inflated as a child of the FrameLayout we added above, which is displayed below the AppBarLayout.
A more detailed information regarding this can be found here.
So your layout will look something like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.sldroids.minidrawer_v3.MainActivity">
<android.support.design.widget.AppBarLayout
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" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<include layout="#layout/content_main" />
</FrameLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>

Related

Problem with displaying top app and contextual action bar in fragment

Initially, I tried to make the context menu appear after a long press on the RecyclerView element of the first fragment.
Then I decided to make it at least appear.
My application consists of three chunks. I am using material design components. The top menu is displayed on the activity layout, and for now it should only change to the contextual menu of the first fragment.
Now the contextual menu is displayed by clicking on the RecyclerView element of the first fragment, but it appears, and the top menu does not disappear.
I need to display Toolbar Material separately on each fragment and somehow replace it with contextual one? Explain, please.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/q1"
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"
tools:context=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/coordinatorLayout2"
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/topmenu"
style="#style/Widget.MaterialComponents.Toolbar.Primary"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:menu="#menu/top_app_bar"
app:navigationIcon="#drawable/ic_baseline_format_list_bulleted_24"
app:title="Главная" />
</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>
<fragment
android:id="#+id/fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView"
android:layout_marginTop="?attr/actionBarSize"
android:layout_marginBottom="?attr/actionBarSize"
app:navGraph="#navigation/my_nav" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_menu"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
MaterialToolbar topBar;
MaterialAlertDialogBuilder madb;
CharSequence sortItems[] = {"По дате", "По важности", "По алфавиту"} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
NavController navController = Navigation.findNavController(this, R.id.fragment);
//AppBarConfiguration appBarConfiguration = AppBarConfiguration(setOf(R.id.firstFragment, R.id.secondFragment, R.id.thirdFragment));
NavigationUI.setupWithNavController(bottomNavigationView, navController);
topBar = findViewById(R.id.topmenu);
madb = new MaterialAlertDialogBuilder(MainActivity.this)
.setTitle("ItsTime")
.setSingleChoiceItems(sortItems, 1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i)
{
case (0):
Toast.makeText(MainActivity.this, "Кнопка 0", Toast.LENGTH_SHORT);
case (1):
Toast.makeText(MainActivity.this, "Кнопка 1", Toast.LENGTH_SHORT);
case (2):
Toast.makeText(MainActivity.this, "Кнопка 2", Toast.LENGTH_SHORT);
}
}
})
.setPositiveButton("Okay, Boomer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "Кнопка ОК", Toast.LENGTH_SHORT);
}
});
topBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId())
{
case (R.id.itemShow):
madb.show();
return true;
}
return false;
}
});
}}
Fragment_First.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
android:scrollbars="vertical"
android:background="#color/colorPrimaryDark"
/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/newEventBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_gravity="bottom|end"
android:layout_margin="32dp"
android:src="#drawable/ic_baseline_add_24"
android:textAllCaps="false"
android:textSize="20sp"
android:textStyle="bold"
app:tint="#FFFFFF">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
And importants part of FirstFragment.java
android.view.ActionMode actionMode = null;
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
//mParam1 = getArguments().getString("name");
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first_new, container, false);
rvEvent = view.findViewById(R.id.recyclerview);
rvEvent.setHasFixedSize(true);
lmEvent = new LinearLayoutManager(this.getContext());
adapterEvent = new EventAdapter(eventsProcess);
rvEvent.setLayoutManager(lmEvent);
adapterEvent.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
eventsProcess.remove(position);
rvEvent.removeViewAt(position);
adapterEvent.notifyItemRemoved(position);
write(getContext(), eventsProcess, PROCESSED_EVENTS);
if (actionMode == null){
actionMode = ((AppCompatActivity) getActivity()).startActionMode(ContextualActionMode);
}
}
});
rvEvent.setAdapter(adapterEvent);
return view;
}
android.view.ActionMode.Callback ContextualActionMode = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater menuInflater = actionMode.getMenuInflater();
menuInflater.inflate(R.menu.contextual_top_app_bar, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.deleteIcon:
Toast.makeText(getContext(), "себевскрой", Toast.LENGTH_SHORT).show();
return true;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
};
Ok, I fixed this by adding this <item name="windowActionModeOverlay">true</item> to the style. But the question remains the same - am I doing the right thing by displaying the top menu in the activity, and displaying the contextual action bar in the fragment?

Fullscreen Dialog Fragment not showing correctly

I've got two problems:
In my app I have an activity with the appbar and a recycler view.
When i click an option of the floating action menu it displays a Fullscreen Dialogfragment but for some reason the dialog is not showing correctly (not totaly fullscreen).
Here is the result
dialogfragment
Also when I click the close button of the Dialog it closes not only the dialog, but the activity as well, and goes to the previous activity.
What should I do. I am beginning Android.
also I want to establish a margin for the cardview (left and right)
Here is my code
Result_contract.java
public class Result_contract extends AppCompatActivity implements
FragmentActions{
String TAG="Result_contract";
private boolean first_time= true;
private List<Contract>lista_contratos;
private FloatingActionsMenu fabm;
private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager lManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_contract);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Contratos");//Set title
getSupportActionBar().setDisplayHomeAsUpEnabled(true);//Enable Back button
fabm= (FloatingActionsMenu)findViewById(R.id.menu_fab);
View fab_buscar = findViewById(R.id.accion_buscar);
fab_buscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showSearchDialog();
}
});
View fab_formulario = findViewById(R.id.accion_formulario);
fab_formulario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDetailsDialog(0);
}
});
recycler = (RecyclerView) findViewById(R.id.reciclador);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
//todo REMOVER ESTO
//SearchContractTask buscar = new SearchContractTask(Contract_query_instance.getInstance().getContractQuery());
//buscar.execute();
SearchContractTask buscar = new SearchContractTask(null);
buscar.execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void showDetailsDialog(int position) {
fabm.collapse();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
Fragment fragment=new Dialog_contract();
Bundle args=new Bundle();
args.putInt("position",position);
fragment.setArguments(args);
transaction.add(android.R.id.content, fragment,"dialog_contract").addToBackStack(null).commit();
}
#Override
public void showSearchDialog() {
fabm.collapse();
}
#Override
public void load_data() {
}
public class SearchContractTask extends AsyncTask<Void, Void, Void> {
Connection cnx;
Models models;
Contract_query query;
public SearchContractTask(Contract_query query) {
super();
cnx = Connection.getConnection();
models= Models.getInstance();
this.query=query;
}
#Override
protected Void doInBackground(Void... voids) {
lista_contratos=Contract_list.getInstance().getList_contract();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (lista_contratos!=null) {
adapter = new Contract_adapter(lista_contratos);
recycler.setAdapter(adapter);
}
else {
//TODO MOSTRAR UN MENSAJE DE QUE NO EXISTEN FILAS EN LA CONSULTA
}
}
#Override
protected void onCancelled() {
}
}
#Override public boolean dispatchTouchEvent(MotionEvent event){
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (fabm.isExpanded()) {
Rect outRect = new Rect();
fabm.getGlobalVisibleRect(outRect);
if(!outRect.contains((int)event.getRawX(), (int)event.getRawY()))
fabm.collapse();
}
}
return super.dispatchTouchEvent(event);
}
#Override
public void onBackPressed() {
if (fabm.isExpanded()) {
fabm.collapse();
}
else{
finish();
}
//super.onBackPressed();
}
}
activity_reult_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.example.ernesto.apptranscargo.Result_contract">
<android.support.design.widget.AppBarLayout
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" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_result_contract" />
<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="#+id/menu_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:fab_labelStyle="#style/Etiquetas"
app:fab_addButtonColorNormal="?attr/colorPrimary"
app:fab_addButtonSize="normal"
app:fab_labelsPosition="left">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/accion_formulario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="?attr/colorAccent"
app:fab_icon="#drawable/ic_tablet"
app:fab_size="normal"
app:fab_title="Formulario" />
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/accion_buscar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="?attr/colorAccent"
app:fab_icon="#drawable/ic_search"
app:fab_size="normal"
app:fab_title="Nueva Búsqueda" />
</com.getbase.floatingactionbutton.FloatingActionsMenu>
</android.support.design.widget.CoordinatorLayout>
content_result_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/reciclador"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="3dp"
android:layout_marginTop="20dp"
android:scrollbars="vertical" />
Dialog_contract.java
public class Dialog_contract extends DialogFragment implements DialogActions {
public static final String TAG = "fragment_dialog";
private TabLayout Tabs;
private Form_contract_detail fragment_detalles;
private Form_contract_observation fragment_obseration;
private Fragment fragment_observation;
View view_contract;
ViewPager pager;
PagerAdapter pagerAdapter;
Toolbar toolbar;
String title="Detalles ";
int cantidad;
public Dialog_contract(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void Dismiss()
{
getDialog().dismiss();
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
cantidad= Contract_list.getInstance().getList_contract().size();
view_contract=inflater.inflate(R.layout.dialog_contract, container, false);
pager=(ViewPager)view_contract.findViewById(R.id.pager);
pagerAdapter= new Dialog_contract_adapter(getActivity(), getChildFragmentManager(),Contract_list.getInstance().getList_contract().size());
toolbar = (Toolbar) view_contract.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setHomeAsUpIndicator(android.R.drawable.ic_menu_close_clear_cancel);
}
setHasOptionsMenu(true);
int position=getArguments().getInt("position", -1);
pager.setAdapter(pagerAdapter);
pager.setPageTransformer(true, new ZoomOutPageTransformer());
//pager.setPageTransformer(true,new DepthPageTransformer() );
pager.setCurrentItem(position);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
updateTitle();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
updateTitle();
return view_contract;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
return dialog;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.dialog_contract_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_next) {
pager.setCurrentItem(pager.getCurrentItem() + 1);
updateTitle();
return true;
} else if (id==R.id.action_previous)
{
pager.setCurrentItem(pager.getCurrentItem() - 1);
updateTitle();
return true;
}
else if (id == android.R.id.home) {
// handle close button click here
dismiss();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void updateTitle() {
toolbar.setTitle(title+String.valueOf(pager.getCurrentItem()+1)+"/"+cantidad);
}
}
dialog_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:paddingTop="24dp"
android:fitsSystemWindows="true"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:fitsSystemWindows="false"
>
<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"
android:fitsSystemWindows="false"/>
</android.support.design.widget.AppBarLayout>
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"/>
</android.support.v4.view.ViewPager>
</LinearLayout>
First of all your dialog layout has top padding so that why it has no full height.
dialog_contract.xml
<android.support.design.widget.CoordinatorLayout
...
android:paddingTop="24dp"
>
Second of all try following java naming convention since your code is realy hard to read
Also when I click the close button of the Dialog it closes not only the dialog, but the activity as well, and goes to the previous activity.
My best guess is that you are not handling menu clicks correctly, try calling
setHasOptionsMenu(true);
from dialogFragmen onCreate

settitle() is not working in android on button clicklistner

I use the setActionBarTitle(); to change the title of the action bar it work fine in onCreate() method but it did not work when i want to implement it on button click listener
public class ScrollingActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
toolbar = (Toolbar) findViewById(R.id.toolbar);
CollapsingToolbarLayout mToolbarlayout= (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
setSupportActionBar(toolbar);
Button newbutton= (Button) findViewById(R.id.changetitle);
if (newbutton != null) {
newbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ScrollingActivity.this, "Hi", Toast.LENGTH_SHORT).show();
setActionBarTitle("HI");
}
});
}
}
public void setActionBarTitle(String title) {
//noinspection ConstantConditions
getSupportActionBar().setTitle(title); //check not working
}
}
The xml which is used for the activity in which i want to change the title
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="appcom.taskremainder.calender.ScrollingActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_scrolling" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_menu_edit"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end" />
</android.support.design.widget.CoordinatorLayout
>
Yes you are right that in onCreate() the Title of ActionBar/ToolBar changes , and if we call the method to change the Title on Button click it doesn't.
The button is defined in the:
<include layout="#layout/content_scrolling"/>
I tried many different ways and stumbled upon this issue https://code.google.com/p/android/issues/detail?id=77763
I have a work around if you would like to try (to change title)
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
android.support.v7.app.ActionBar actionBar;
CollapsingToolbarLayout mToolbarlayout;
Button newButton;
// On every click I will change the value of i
static int i=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbarlayout= (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
newButton= (Button) findViewById(R.id.changetitle);
setSupportActionBar(toolbar);
actionBar=getSupportActionBar();
newButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//oldWay();
newWay();
}
});
}
private void oldWay() {
Toast.makeText(MainActivity.this, ""+actionBar.getTitle(), Toast.LENGTH_SHORT).show();
actionBar.setTitle("Something Else");
Toast.makeText(MainActivity.this/, ""+actionBar.getTitle(), Toast.LENGTH_SHORT).show();
//Toast says that value has changed, but it doesn't on screen
}
private void newWay() {
mToolbarlayout.setTitle("" + i++);
}
}
Let me know if this helps or not.

The ViewPager doesn't scroll at al after refreshing the data

I have an activity which has a coordinator layout with viewpager and CircularPager Indicator. I am trying to use MaterialRefreshLayout Library to do pull to refresh
The library can be found at Pull to refresh library
However, after I use pull to refresh my data, the viewpager just doesn't update the rest of the fragment and hence it dosn't scroll. Once I do background foreground it scrolls alright. Below is the Layout and activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="myPackage.HomeActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
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:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<com.cjj.MaterialRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:overlay="true"
app:progress_show_arrow="true"
app:wave_show="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_marginTop="65dp"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="#dimen/viewpager_height_none"
android:layout_weight="1"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<mypackage.ui.CirclePageIndicator
android:id="#+id/indicator"
style="#style/PageIndicator"
android:clickable="false"
app:fillColor="#color/default_circle_indicator_stroke_color"
app:pageColor="#color/circlepageindicator_fill_color"
app:radius="#dimen/circlepageindicator_radius" />
</LinearLayout>
</com.cjj.MaterialRefreshLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
And Below is the Activity
public class HomeActivity extends AppCompatActivity {
private SectionPagerAdapter mSectionPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private CirclePageIndicator mPagerCountIndicator;
private MaterialRefreshLayout materialRefreshLayout;
private Integer mTaskCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Bundle extras = getIntent().getExtras();
if(extras != null) {
mTaskCount= extras.getInt("task_Count");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
updateandShowViewPager();
materialRefreshLayout = (MaterialRefreshLayout) findViewById(R.id.refresh);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
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();
}
});
}
#Override
protected void onResume() {
super.onResume();
materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
#Override
public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
refresh();
}
});
materialRefreshLayout.finishRefresh();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
private void startMyAsyncTask(AsyncTask asyncTask){
//execute my AsyncTask and call Update and Show ViewPager
}
private void updateandShowViewPager(){
AsyncTaskCallBack asyncTaskCallBack = new AsyncTaskCallBack() {
#Override
public void onSuccess() {
displayViewPager();
}
}
};
for(int taskCount = 1; taskCount <= mTaskCount; taskCount ++){
myAsyncTask = new MyAsyncTask();
startMyAsyncTask(myAsyncTask );
}
}
private void displayViewPager(){
mSectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionPagerAdapter);
mTaskCountIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
mTaskCountIndicator .setViewPager(mViewPager);
}
private void refresh() {
MyAsyncTask myAsyncTask = null;
MyAsyncTaskCallBack myAsyncTaskCallBack = new MyAsyncTaskCallBack () {
#Override
public void onSuccess() {
updateViewPager();
}
}
};
for(int taskCount = 1; taskCount <= mTaskCount; taskCount ++){
myAsyncTask = new MyAsyncTask();
startMyAsyncTask(myAsyncTask );
}
}
private void updateViewPager(){
mSectionPagerAdapter.setPagerItem(myMap);
mSectionPagerAdapter.notifyDataSetChanged();
mCartCountIndicator.notifyDataSetChanged();
mViewPager.invalidate();
}
}
Not Sure what am I doing wrong here. Appreciate any suggestion.
use
mViewPager.setOffscreenPageLimit(numberOfPages);
Okay, figured since it is the activity that is not being refreshed itself I tried this.onResume() in the refresh method once I do notifyDataSetChanged(). It works.
Not sure it is the cleanest solution though

Android - CollapsingToolbarLayout display menu items only on top

I try to hide menu items when the CollapsingToolbarLayout is open.
I've do this: XML
<android.support.design.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" android:fitsSystemWindows="true"
tools:context="com.compafone.app.ViewNews">
<android.support.design.widget.AppBarLayout android:id="#+id/app_bar"
android:fitsSystemWindows="true" android:layout_height="#dimen/app_bar_height"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout android:id="#+id/toolbar_layout"
android:fitsSystemWindows="true" android:layout_width="match_parent"
android:scaleType="centerCrop" android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:layout_height="match_parent" app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:contentScrim="?attr/colorPrimary">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_height="?attr/actionBarSize" android:layout_width="match_parent"
app:layout_collapseMode="pin" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_view_news" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin" app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end" android:src="#drawable/chatboxes" />
And this is the XML menu:
<menu 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" tools:context="com.compafone.app.ViewNews">
<item
android:id="#+id/action_comments"
android:title="Comments"
android:orderInCategory="200"
android:icon="#drawable/chatboxes"
app:showAsAction="ifRoom" />
<item
android:id="#+id/menu_item_share"
android:title="Partager"
android:icon="#android:drawable/ic_menu_share"
android:orderInCategory="100"
app:showAsAction="ifRoom"/>
Then, this is the Java activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.arrowleft);
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();
}
});
//On récupère l'intent
Intent i = getIntent();
id = i.getStringExtra("ID");
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
collapsingToolbarLayout.setTitle("Compafone");
appbar = (AppBarLayout) findViewById(R.id.app_bar);
new NewsListActivityLoad().execute();
title = (TextView) findViewById(R.id.news_title);
content = (TextView) findViewById(R.id.news_content);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu resource
getMenuInflater().inflate(R.menu.menu_view_news, menu);
MenuItem menuItem = menu.findItem(R.id.menu_item_share);
//mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
this.overridePendingTransition(0, R.anim.abc_fade_out);
return true;
case R.id.action_comments:
Intent intent = getIntent();
//Intent intent3 = new Intent(this, comments.class);
try {
//intent3.putExtra(Intent_ID, intent.getStringExtra(EXTRA_PROJET));
//intent3.putExtra(Intent_SUCCES, "null");
//startActivity(intent3);
} catch (Exception e) {
Log.i("notFoundProject", "Le projet n'existe pas");
}
return true;
case R.id.menu_item_share:
//doShare(shareintent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
So, I want to hide items from menu and display items only when users scroll down (When toolbar is in normal size, so display items at the same time when toolbar title is show in the toolbar).
Sorry for bad english, thanks in advance.

Categories

Resources