I want to customize the popupmenu in android, default popup menu gives more space ,so I'm trying to change the custom layout in popup menu but I cant figure out how.
Note: I want to do this small popup design so I go with default popup menu but i want to customize it.
findViewById(R.id.menuclick).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popupMenu = new PopupMenu(Sample1.this, view);
popupMenu.setOnMenuItemClickListener(Sample1.this);
popupMenu.inflate(R.layout.menus_layout);
popupMenu.show();
}
});
To inflate popupMenu from a button onClick, use the following code.
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, v);
popup.getMenuInflater().inflate(R.menu.pop_up, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, "Some Text" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();//showing popup menu
}
});
EDIT
To style the popupMenu, add the following style.
<style name="PopupMenu" parent="#android:style/Widget.PopupMenu">
<item name="android:popupBackground">#ffffff</item>
</style>
I noticed you also want to add icons next to your text. It is possible to add icons in popupMenu. However it is a better approach to use popup Window instead. Here is a sample code:
PopupWindow mypopupWindow;
setPopUpWindow();
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mypopupWindow.showAsDropDown(v,-153,0);
//showAsDropDown(below which view you want to show as dropdown,horizontal position, vertical position)
}
}
});
}
private void setPopUpWindow() {
LayoutInflater inflater = (LayoutInflater)
getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.popup, null);
Start=(RelativeLayout)view.findViewById(R.id.start_btn);
Pause=(RelativeLayout)view.findViewById(R.id.pause_btn);
Stop=(RelativeLayout)view.findViewById(R.id.stop_btn);
mypopupWindow = new PopupWindow(view,300, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
popup Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:background="#drawable/whitedrawable"
android:paddingRight="0dp"
android:layout_marginRight="0dp"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/startimg"
android:id="#+id/startimg"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
/>
<TextView
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="0dp"
android:text="Start"
android:layout_toRightOf="#+id/startimg"
/>
<!-- Continue for other items-->
The whitedrawable can be used to set a background of your choice. You can use 9patch to get the shadow and rounded corners for the background.
To dismiss the popupWindow, use the following code:
mypopupWindow.getContentView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mypopupWindow.dismiss();
}
});
To dismiss using the back button, use:
#Override
public void onBackPressed() {
if(mypopupWindow.isShowing()) {
mypopupWindow.dismiss();
return;
}
super.onBackPressed();
}
My answer will be like an update for this answer (the first answer in this post) focusing at PopupWindow using Kotlin, also using View Binding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val bind = ViewBinding.inflate(inflater, container, false)
val popupInflater =
requireActivity().applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflaterERVICE) as LayoutInflater
val popupBind = YourPopupLayoutBinding.inflate(popupInflater)
popupBind.icon1.setOnClickListener { // do your thing for 1st icon }
popupBind.icon2.setOnClickListener { // do your thing for 2nd icon }
val popupWindow = PopupWindow(
popupBind.root, 126.fromDpToPx.toInt(),
89.fromDpToPx.toInt(), true
).apply { contentView.setOnClickListener { dismiss() } }
// make sure you use number than wrap_content or match_parent,
// because for me it is not showing anything if I set it to wrap_content from ConstraintLayout.LayoutParams.
bind.yourButton.setOnClickListener(popupWindow::showAsDropDown)
return bind.root
}
This code is in Fragment class, that's why I call applicationContext using requireActivity()
Here is the code for layout,
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="126dp"
android:layout_height="89dp"
android:background="#FFFFFF">
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/icon1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:drawablePadding="8dp"
android:paddingHorizontal="10dp"
android:paddingVertical="10dp"
android:text="#string/tokopedia"
android:textColor="#color/dark_grey"
app:drawableStartCompat="#drawable/ic_icon1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/icon2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:drawablePadding="8dp"
android:paddingHorizontal="10dp"
android:paddingVertical="10dp"
android:text="#string/shopee"
android:textColor="#color/dark_grey"
app:drawableStartCompat="#drawable/ic_icon2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/icon1" />
</androidx.constraintlayout.widget.ConstraintLayout>
Don't forget to add background color in custom layout, also you can styling freely in custom layout.
Hope this can help you all :)
Related
I am creating an android application in which i want to use Snack Bar,
In a that snack bar i want 2 different words on which we have to perform 2 different actions.
From the Google design specifications:
Each snackbar may contain a single action, neither of which may be “Dismiss” or “Cancel.”
For multiple actions, use a dialog.
Thanks Shailesh, I had to modify the code in order to make it work for me.
my_snackbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:id="#+id/my_snackbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dark_grey"
android:padding="15dp">
<TextView
android:id="#+id/message_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".6"
android:gravity="center_vertical"
android:text="Two button snackbar"
android:textColor="#color/white"/>
<TextView
android:id="#+id/first_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".2"
android:gravity="center"
android:text="ONE"
android:textColor="#FFDEAD"/>
<TextView
android:id="#+id/second_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".2"
android:gravity="center"
android:text="TWO"
android:textColor="#FFDEAD"/>
</LinearLayout>
In your activity call this method whenever you want to show the snackbar:
private void showTwoButtonSnackbar() {
// Create the Snackbar
LinearLayout.LayoutParams objLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
snackbar = Snackbar.make(this.findViewById(android.R.id.content), message, Snackbar.LENGTH_INDEFINITE);
// Get the Snackbar layout view
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
// Set snackbar layout params
int navbarHeight = getNavBarHeight(this);
FrameLayout.LayoutParams parentParams = (FrameLayout.LayoutParams) layout.getLayoutParams();
parentParams.setMargins(0, 0, 0, 0 - navbarHeight + 50);
layout.setLayoutParams(parentParams);
layout.setPadding(0, 0, 0, 0);
layout.setLayoutParams(parentParams);
// Inflate our custom view
View snackView = getLayoutInflater().inflate(R.layout.my_snackbar, null);
// Configure our custom view
TextView messageTextView = (TextView) snackView.findViewById(R.id.message_text_view);
messageTextView.setText(message);
TextView textViewOne = (TextView) snackView.findViewById(R.id.first_text_view);
textViewOne.setText("ALLOW");
textViewOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Allow", "showTwoButtonSnackbar() : allow clicked");
snackbar.dismiss();
}
});
TextView textViewTwo = (TextView) snackView.findViewById(R.id.second_text_view);
textViewTwo.setText("DENY");
textViewTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Deny", "showTwoButtonSnackbar() : deny clicked");
snackbar.dismiss();
}
});
// Add our custom view to the Snackbar's layout
layout.addView(snackView, objLayoutParams);
// Show the Snackbar
snackbar.show();
}
To get nav bar height:
public static int getNavBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
As #Elias N answer's each Snackbar may contain a single action. If you want to set more then action in Snackbar then you need to create your own layout. Please try this i hope this will help you.
Create one xml file my_snackbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#000000">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight=".7"
android:gravity="center_vertical"
android:text="Please select any one"
android:textColor="#color/white"/>
<TextView
android:id="#+id/txtOne"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight=".1"
android:gravity="center"
android:text="ONE"
android:textColor="#color/red"/>
<TextView
android:id="#+id/txtTwo"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight=".1"
android:gravity="center"
android:text="TWO"
android:textColor="#color/red"/>
</LinearLayout>
Now in your activity file do the following code.
public void myCustomSnackbar()
{
// Create the Snackbar
LinearLayout.LayoutParams objLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Snackbar snackbar = Snackbar.make(llShow, "", Snackbar.LENGTH_LONG);
// Get the Snackbar's layout view
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
layout.setPadding(0,0,0,0);
// Hide the text
TextView textView = (TextView) layout.findViewById(android.support.design.R.id.snackbar_text);
textView.setVisibility(View.INVISIBLE);
LayoutInflater mInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
// Inflate our custom view
View snackView = getLayoutInflater().inflate(R.layout.my_snackbar, null);
// Configure the view
TextView textViewOne = (TextView) snackView.findViewById(R.id.txtOne);
textViewOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("One", "First one is clicked");
}
});
TextView textViewTwo = (TextView) snackView.findViewById(R.id.txtTwo);
textViewTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Two", "Second one is clicked");
}
});
// Add the view to the Snackbar's layout
layout.addView(snackView, objLayoutParams);
// Show the Snackbar
snackbar.show();
}
For more detail please read this documentation and here.
You can use BottomSheetDialog and disguise it as a SnackBar. Only difference would be that it will be dismissed by swiping down instead of right and it can stay there until user dismissed it while SnackBar eventually fades away.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_history_menu_bottom"
style="#style/Widget.Design.BottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:background="#color/cardview_dark_background"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/appCompatTextView"
android:layout_width="wrap_content"
android:layout_height="19dp"
android:layout_gravity="center_vertical"
android:layout_marginStart="8dp"
android:layout_weight="0.6"
android:text="Load More ?"
android:textAppearance="#style/TextAppearance.Design.Snackbar.Message"
android:textColor="#color/cardview_light_background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/fragment_history_bottom_sheet_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|end"
android:layout_weight="0.4"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<android.support.v7.widget.AppCompatButton
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes" />
<android.support.v7.widget.AppCompatButton
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No"
android:textColor="#color/cardview_light_background" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
and use it as following (Kotlin)
val dialog = BottomSheetDialog(this)
dialog.setContentView(this.layoutInflater.inflate(R.layout.bottom_sheet_load_prompt,null))
dialog.show()
result will be similar to SnackBar
Here is a proper solution with Kotlin I first deployed it when working on Fulguris.
Using Kotlin extension we expand our Snackbar class as follows:
/**
* Adds an extra action button to this snackbar.
* [aLayoutId] must be a layout with a Button as root element.
* [aLabel] defines new button label string.
* [aListener] handles our new button click event.
*/
fun Snackbar.addAction(#LayoutRes aLayoutId: Int, #StringRes aLabel: Int, aListener: View.OnClickListener?) : Snackbar {
addAction(aLayoutId,context.getString(aLabel),aListener)
return this;
}
/**
* Adds an extra action button to this snackbar.
* [aLayoutId] must be a layout with a Button as root element.
* [aLabel] defines new button label string.
* [aListener] handles our new button click event.
*/
fun Snackbar.addAction(#LayoutRes aLayoutId: Int, aLabel: String, aListener: View.OnClickListener?) : Snackbar {
// Add our button
val button = LayoutInflater.from(view.context).inflate(aLayoutId, null) as Button
// Using our special knowledge of the snackbar action button id we can hook our extra button next to it
view.findViewById<Button>(R.id.snackbar_action).let {
// Copy layout
button.layoutParams = it.layoutParams
// Copy colors
(button as? Button)?.setTextColor(it.textColors)
(it.parent as? ViewGroup)?.addView(button)
}
button.text = aLabel
/** Ideally we should use [Snackbar.dispatchDismiss] instead of [Snackbar.dismiss] though that should do for now */
//extraView.setOnClickListener {this.dispatchDismiss(BaseCallback.DISMISS_EVENT_ACTION); aListener?.onClick(it)}
button.setOnClickListener {this.dismiss(); aListener?.onClick(it)}
return this;
}
We then need to define our button resource:
<?xml version="1.0" encoding="utf-8"?>
<!--
Used to create and extra button in our snackbar popup messages.
Though most properties including layout params and colors are overridden at runtime.
They are just copied from the standard snackbar action button to make sure they both lookalike.
-->
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/snackbar_extra_action"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginStart="0dp"
android:layout_gravity="center_vertical|right|end"
android:paddingTop="14dp"
android:paddingBottom="14dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:textColor="?attr/colorAccent"
style="?attr/borderlessButtonStyle"/>
Here is how you use it:
Snackbar.make(aView, aMessage, aDuration).setAction(R.string.button_one) {
// Do your thing after regular button press
}.addAction(R.layout.snackbar_extra_button, R.string.button_two){
//Do your thing after extra button push
}.show()
Another hacky workaround you could try (works in my case).
final Snackbar snackbar = Snackbar.make(view, "UNDO MARKED AS READ", Snackbar.LENGTH_LONG);
snackbar.setAction("DISMISS", new View.OnClickListener() {
#Override
public void onClick(View v) {
if (snackbar != null)
snackbar.dismiss();
}
});
View snackbarView = snackbar.getView();
int snackbarTextId = android.support.design.R.id.snackbar_text;
TextView textView = (TextView) snackbarView.findViewById(snackbarTextId);
textView.setTextColor(Color.WHITE);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (snackbar != null)
snackbar.dismiss();
// undo mark as unread code
}
});
snackbar.show();
Following Shaileshs solution:
snackbar class
public class SnackbarOfflineErrorNotification {
/**
* A view from the content layout.
*/
#NonNull
private final View view;
#NonNull
private Context context;
/**
* The snack bar being shown.
*/
#Nullable
private Snackbar snackbar = null;
/**
* Construct a new instance of the notification.
*
* #param view A view from the content layout, used to seek an appropriate anchor for the
* Snackbar.
*/
public SnackbarOfflineErrorNotification(#NonNull final View view, #NonNull Context context) {
this.view = view;
this.context = context;
}
public void showOfflineError (){
if (snackbar == null){
//create snackbar
snackbar = Snackbar.make(this.view, R.string.offline_text, LENGTH_INDEFINITE);
// Create the Snackbar
LinearLayout.LayoutParams objLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// Get the Snackbar's layout view
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
layout.setPadding(0,0,0,0);
// Hide the text
TextView textView = (TextView) layout.findViewById(android.support.design.R.id.snackbar_text);
textView.setVisibility(View.INVISIBLE);
// Inflate our custom view
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View snackView = inflater.inflate(R.layout.snackbar_offline, null);
// Configure the view
Button btnOne = (Button) snackView.findViewById(R.id.btnOne);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// action 1
}
});
Button btnTwo = (Button) snackView.findViewById(R.id.btnTwo);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// action 2
}
});
// Add the view to the Snackbar's layout
layout.addView(snackView, objLayoutParams);
// Show the Snackbar
snackbar.show();
}
}
/**
* Hides the currently displayed error.
*/
public void hideError() {
if (snackbar != null) {
snackbar.dismiss();
snackbar = null;
}
}
}
snackbar xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#000000">
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_weight=".7"
android:gravity="center_vertical"
android:text="offline"
android:textColor="#color/white"
android:paddingLeft="16dp"/>
<Button
android:id="#+id/btnOne"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_weight=".1"
android:gravity="center"
android:text="one" />
<Button
android:id="#+id/btnTwo"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_weight=".1"
android:gravity="center"
android:text="two"/>
</LinearLayout>
target activity
constructor(){
snackbarOfflineErrorNotification = new SnackbarOfflineErrorNotification(findViewById(R.id.coordinator_layout), getApplicationContext());
}
public void hideSnackbar(){
snackbarOfflineErrorNotification.hideError();
}
public showSnackbar(){
snackbarOfflineErrorNotification.showOfflineError();
}
You can use "dismiss" as another actions
Snackbar snackbar = Snackbar.make(requireView(), "Marked as read", BaseTransientBottomBar.LENGTH_SHORT);
snackbar.setAction("undo", view -> {
//undo action
});
snackbar.addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar transientBottomBar, int event) {
//dismiss action
}
});
snackbar.show();
I am absolute beginner to Android. Now I am having a problem with setting the width of default AlertDialog with custom view in Android. It is not resizing the width of the alert dialog. What is wrong with my code ?
This is the view layout of my alert dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<android.support.v7.widget.AppCompatButton
xmlns:app="http://schemas.android.com/apk/res-auto"
android:textColor="#color/white"
app:backgroundTint="#color/green"
android:layout_gravity="center_horizontal"
android:id="#+id/btn_row_option_done"
android:text="Done"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatButton
android:textColor="#color/white"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:backgroundTint="#color/lightBlue"
android:layout_gravity="center_horizontal"
android:text="Edit"
android:id="#+id/btn_row_option_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatButton
android:textColor="#color/white"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:backgroundTint="#color/red"
android:layout_gravity="center_horizontal"
android:text="Delete"
android:id="#+id/btn_row_option_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatButton
xmlns:app="http://schemas.android.com/apk/res-auto"
app:backgroundTint="#color/white"
android:layout_gravity="center_horizontal"
android:text="Cancel"
android:id="#+id/btn_row_option_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
As you can see, I set the width of the linearLayout to wrap_content.
This is how I am opening the alert dialog in my Java code
public void showOptionDialog(final int id)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_option_dialog, null);
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
Boolean isTaskDone = dbHelper.isTaskDone(id);
Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
if(isTaskDone==false)
{
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(id);
refreshListView();
alertDialog.cancel();
Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
}
});
}
else{
ViewGroup viewGroup = (ViewGroup)doneBtn.getParent();
viewGroup.removeView(doneBtn);
}
Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
if(isTaskDone==false)
{
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
activity.replaceEditTaskFragment(id);
alertDialog.cancel();
}
});
}
else{
ViewGroup viewGroup = (ViewGroup)editBtn.getParent();
viewGroup.removeView(editBtn);
}
Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteTask(id);
items.remove(optionFocusedItemIndex);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
alertDialog.cancel();
updateListEmptyText();
}
});
Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.cancel();
}
});
alertDialog.setView(view);
alertDialog.show();
}
But when the alert dialog is opened, its width is not resized and still showing the default size like in screenshot.
This is the screenshot.
As you can see, width is nearly full of screen even I did set to wrap_content. I also set something like 300px. It is not working. How can I achieve this?
First make other layout for container and inside it make this linear layout with wrap content. After that you can make your alpha background of the container almost to 0 to be transparent. The dialog inside with the buttons is on the inner layout. For custom dialog you cant use this AlertDialog, make your own activity which behavior is like a dialog.
set required size here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="300px"
android:layout_height="match_parent">......</LinearLayout>
or
alertDialog.show();
alertDialog.getWindow().setLayout(300, 300);
Change this line
alertDialog.setView(view);
To
alertDialog.setContentView(view);
Here view is the instance of your custom layout.
I tried to find an answer for myself but couldn't find it.
I need make badge on the MenuItem icon in the Toolbar, like this:
How can I make this?
Here is step by step functionality:
add menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/actionNotifications"
android:icon="#drawable/ic_info_outline_white_24dp"
android:menuCategory="secondary"
android:orderInCategory="1"
android:title="Cart"
app:actionLayout="#layout/notification_layout"
app:showAsAction="always" />
</menu>
Then add notification_layout.xml, this layout will be used as the notification icons layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="#android:style/Widget.ActionButton"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#android:color/transparent"
android:clickable="true"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/hotlist_bell"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:contentDescription="Notification Icon"
android:gravity="center"
android:src="#drawable/ic_info_outline_white_24dp" />
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/txtCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/x5dp"
android:layout_marginLeft="#dimen/x10dp"
android:layout_marginRight="0dp"
android:background="#drawable/pointer_"
android:gravity="center"
android:minWidth="17sp"
android:text="0"
android:textColor="#ffffffff"
android:textSize="12sp" />
</RelativeLayout>
now inside Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
final View notificaitons = menu.findItem(R.id.actionNotifications).getActionView();
txtViewCount = (TextView) notificaitons.findViewById(R.id.txtCount);
updateHotCount(count++);
txtViewCount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateHotCount(count++);
}
});
notificaitons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO
}
});
return true;
}
You can put following function (taken from stackoverflow) inside the activity to update counter:
public void updateHotCount(final int new_hot_number) {
count = new_hot_number;
if (count < 0) return;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (count == 0)
txtViewCount.setVisibility(View.GONE);
else {
txtViewCount.setVisibility(View.VISIBLE);
txtViewCount.setText(Integer.toString(count));
// supportInvalidateOptionsMenu();
}
}
});
}
I think it is possible with :
<ImageView
android:id="#+id/counterBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/unread_background" /> <!-- your icon -->
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textSize="8sp"
android:layout_centerInParent="true"
android:textColor="#FFFFFF" />
And then using it for that icon as background.also, you need to remove/disable the default icon too.
You may want to take a look:
Remove App Icon from Navigation Drawer ActionBar Does not work
Remove the navigation drawer icon and use the app icon to open
https://stackoverflow.com/a/29160904/4409113
Also, in the android-sdk/platforms/android-22/data/res, there should be that icon. You just need to find that and use it for your purpose (for example, adding that ImageView and adding it asbackground)
Take a look: https://stackoverflow.com/a/34999691/4409113
MaterialToolbar has ability to add BadgeDrawable:
For example in your Activity you can add the badge like this:
val toolbar: MaterialToolbar = findViewById(R.id.toolbar)
val badgeDrawable = BadgeDrawable.create(this).apply {
isVisible = true
backgroundColor = neededBadgeColor
number = neededNumber
}
BadgeUtils.attachBadgeDrawable(badgeDrawable, toolbar, R.id.item_in_toolbar_menu)
I have a problem that I am designing a custom dialog for this. I am creating a xml for this as Framelayout is the root layout, and another framelayout with a gray background image is used for the contents, in which I have added a textview and two buttons Ok and Cancel and use all of this through dialog.setContentView(desired Xml Resource);
But when I generate that particular dialog then it shows extra spaces from each side, or we can say that extra margins are there but I don't know how it will removed? Please review the image attached with this question and suggest me the right solution.
Xml Layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content">
<FrameLayout android:id="#+id/rel"
android:layout_gravity="center_vertical" android:background="#drawable/dialog_box_bg" android:layout_width="wrap_content" android:layout_height="189dp">
<TextView android:id="#+id/tv_LogoutDialog_Text"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#424242"
android:text="Are you sure want to logout?" android:textSize="20dip" android:layout_gravity="center_vertical|center_horizontal"></TextView>
<Button android:id="#+id/btn_LogoutDialog_Cancel" android:background="#drawable/dialog_cancel_btn"
android:layout_marginLeft="20dip" android:layout_width="120dip" android:layout_height="42dip" android:layout_gravity="bottom|left" android:layout_marginBottom="15dip"></Button>
<Button android:id="#+id/btn_LogoutDialog_Ok"
android:background="#drawable/dialog_ok_btn_hover"
android:layout_width="120dip"
android:layout_height="42dip" android:layout_marginLeft="180dip" android:layout_gravity="bottom|right" android:layout_marginBottom="15dip" android:layout_marginRight="20dip"></Button>
</FrameLayout>
</FrameLayout>
Code:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
dialog = new Dialog(HomeScreenActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.logoutdialog);
btn_cancel = (Button)dialog.findViewById(R.id.btn_LogoutDialog_Cancel);
btn_ok = (Button)dialog.findViewById(R.id.btn_LogoutDialog_Ok);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dismissDialog(0);
}
});
btn_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(HomeScreenActivity.this,LoginScreen.class);
startActivity(intent);
}
});
return dialog;
}
return null;
}
Thanks in advance.
Don't use
dialog.setContentView(R.layout.logoutdialog);
use
LayoutInflater class to set Dialog content view
Here is link (Check) you can get the idea May this helps you.
Change it by adding a parameter false like in the code below.
dialog.customView(R.layout.dialog_blueprint, false)
The second argument (false) is wrapTheDialogBoxInScrollView. If the content in the dialog box is small and does not require a ScrollView set it to false.
Is it possible to have just an image popup/come-up in an Android application? It's similar to an overriding the normal view of an AlertDialog so that it contains just an image and nothing else.
SOLUTION: I was able to find an answer thanks to #blessenm's help. Masking an activity as a dialog seems to be the ideal way. The following is the code that I have used. This dialog styled activity can be invoked as needed by the application the same way a new activity would be started
ImageDialog.java
public class ImageDialog extends Activity {
private ImageView mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_dialog_layout);
mDialog = (ImageView)findViewById(R.id.your_image);
mDialog.setClickable(true);
//finish the activity (dismiss the image dialog) if the user clicks
//anywhere on the image
mDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
your_dialog_layout.xml
<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/image_dialog_root"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:gravity = "center">
<ImageView
android:id="#+id/your_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src = "#drawable/your_image_drawable"/>
</FrameLayout>
It is crucial that you set the following style for the activity to accomplish this:
styles.xml
<style name="myDialogTheme" parent="#android:style/Theme.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFrame">#null</item>
<item name="android:background">#android:color/transparent</item>
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
<item name="android:windowContentOverlay">#null</item>
</style>
The final step is to declare this style for the activity in the manifest as follows:
<activity android:name=".ImageDialog" android:theme="#style/myDialogTheme" />
No xml:
public void showImage() {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
imageView.setImageURI(imageUri);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
If you just want to use a normal dialog something like this should work
Dialog settingsDialog = new Dialog(this);
settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
settingsDialog.setContentView(getLayoutInflater().inflate(R.layout.image_layout
, null));
settingsDialog.show();
image_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:src="YOUR IMAGE"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="OK" android:onClick="dismissListener"/>
</LinearLayout>
Try the following:
It has image zoom_in/zoom_out as well.
Step 1:
Add compile 'com.github.chrisbanes.photoview:library:1.2.4' to your build.gradle
Step 2:
Add the following xml
custom_fullimage_dialoge.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root" android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:padding="10dp">
<ImageView android:id="#+id/fullimage" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ImageView>
<TextView android:id="#+id/custom_fullimage_placename"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:textColor="#FFF">
</TextView>
</LinearLayout>
Step 3:
private void loadPhoto(ImageView imageView, int width, int height) {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
//dialog.setContentView(R.layout.custom_fullimage_dialog);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_fullimage_dialog,
(ViewGroup) findViewById(R.id.layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
image.setImageDrawable(imageView.getDrawable());
image.getLayoutParams().height = height;
image.getLayoutParams().width = width;
mAttacher = new PhotoViewAttacher(image);
image.requestLayout();
dialog.setContentView(layout);
dialog.show();
}
Step 4:
user_Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
loadPhoto(user_Image,width,height);
}
});
You can do it easily by create a Dialog Fragment in Kotlin:
BigImageDialog.kt
class BigImageDialog():DialogFragment() {
private var imageUrl = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
imageUrl = arguments.getString("url")
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
val v = inflater!!.inflate(R.layout.dialog_big_image, container, false)
this.dialog.window.requestFeature(Window.FEATURE_NO_TITLE)
Picasso.get().load(imageUrl).into(v.bigImageView)
return v
}
override fun onStart() {
super.onStart()
val dialog = dialog
if (dialog != null) {
dialog.window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
}
companion object {
#JvmStatic
fun newInstance(imageUrl: String) =
BigImageDialog().apply {
arguments = Bundle().apply {
putString("url", imageUrl)
}
}
}
}
dialog_big_image.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/bigImageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Opening Dialog:
"smallImageView".setOnClickListener { BigImageDialog.newInstance("image url").show(fragmentManager,"") }
There is a couple ways you can do this. But, if you're looking to have your image appear to be floating above your existing activity, you may want to use an activity with android:theme="#style/Theme.Transparent" defined in the manifest. Then, design your layout to just have a single ImageView positioned in the center of the screen. The user will have to push the back button to get out of this, but it sounds like that's what you want.
If you want it to look like an actual dialog, you can always use a dialog styled activity as well using Theme.Dialog. OR, you could just use a dialog and customize it.
The more flexible and recommended way is use DialogFragment. If you want to support versions before 3.0 you can use compatibility library