Show icons on dropdown menu on a layout [duplicate] - java

I really like the new PopupMenu we got in 3.0, but I just can't display any icons next to the menu items in it. I'm inflating the menu from the .xml below:
<item android:id="#+id/menu_delete_product"
android:icon="#drawable/sym_action_add"
android:title="delete"
android:showAsAction="ifRoom|withText" />
<item android:id="#+id/menu_modify_product"
android:icon="#drawable/sym_action_add"
android:title="modify"
android:showAsAction="ifRoom|withText" />
<item android:id="#+id/menu_product_details"
android:icon="#drawable/sym_action_add"
android:title="details"
android:showAsAction="ifRoom|withText" />
With this code:
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu pop = new PopupMenu(getActivity(), v);
pop.getMenuInflater().inflate(R.menu.shelves_details_menu, pop.getMenu());
pop.show();
}
});
I can't get the icons to show up, am I missing something?

Contribution to the solution provided by Gaelan Bolger.
Use this code if you get a "IllegalAccessException: access to field not allowed".
PopupMenu popup = new PopupMenu(mContext, view);
try {
Field[] fields = popup.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(popup);
Class<?> classPopupHelper = Class.forName(menuPopupHelper
.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod(
"setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
prepareMenu(popup.getMenu());
popup.show();
text

If you're willing to be a bit adventurous, look at Google's source code for PopupMenu. Create your own class i.e. MyPopupMenu that is the same as Google's PopupMenu class, but make one slight change.
In PopupMenu's constructor:
public MyPopupMenu(Context context, View anchor) {
// TODO Theme?
mContext = context;
mMenu = new MenuBuilder(context);
mMenu.setCallback(this);
mAnchor = anchor;
mPopup = new MenuPopupHelper(context, mMenu, anchor);
mPopup.setCallback(this);
mPopup.setForceShowIcon(true); //ADD THIS LINE
}
use the method setForceShowIcon to force it to show the icon. You can also just expose a public method to set this flag as well depending on your needs.

I was able to show the icons using reflection. It may not be the most elegant solution but it works.
try {
Class<?> classPopupMenu = Class.forName(popupMenu
.getClass().getName());
Field mPopup = classPopupMenu.getDeclaredField("mPopup");
mPopup.setAccessible(true);
Object menuPopupHelper = mPopup.get(popupMenu);
Class<?> classPopupHelper = Class.forName(menuPopupHelper
.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod(
"setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
} catch (Exception e) {
e.printStackTrace();
}

We can use sub-menu model. So, we don't need to write method for showing popup menu, it will be showing automacally. Have a look:
menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_more"
android:icon="#android:drawable/ic_menu_more"
android:orderInCategory="1"
android:showAsAction="always"
android:title="More">
<menu>
<item
android:id="#+id/action_one"
android:icon="#android:drawable/ic_popup_sync"
android:title="Sync"/>
<item
android:id="#+id/action_two"
android:icon="#android:drawable/ic_dialog_info"
android:title="About"/>
</menu>
</item>
</menu>
in MainActivity.java
#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;
}
The result is:

before use method popup.show(),make a MenuPopupHelper instance and call method setForceShowIcon(true),like this
try {
Field mFieldPopup=popupMenu.getClass().getDeclaredField("mPopup");
mFieldPopup.setAccessible(true);
MenuPopupHelper mPopup = (MenuPopupHelper) mFieldPopup.get(popupMenu);
mPopup.setForceShowIcon(true);
} catch (Exception e) {
}

The easiest way I found is that to use MenuBuilder and MenuPopupHelper.
MenuBuilder menuBuilder =new MenuBuilder(this);
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.menu, menuBuilder);
MenuPopupHelper optionsMenu = new MenuPopupHelper(this, menuBuilder, view);
optionsMenu.setForceShowIcon(true);
// Set Item Click Listener
menuBuilder.setCallback(new MenuBuilder.Callback() {
#Override
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
switch (item.getItemId()) {
case R.id.opt1: // Handle option1 Click
return true;
case R.id.opt2: // Handle option2 Click
return true;
default:
return false;
}
}
#Override
public void onMenuModeChange(MenuBuilder menu) {}
});
// Display the menu
optionsMenu.show();
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/opt1"
android:icon="#mipmap/ic_launcher"
android:title="option 1" />
<item
android:id="#+id/opt2"
android:icon="#mipmap/ic_launcher"
android:title="option 2" />
</menu>

I found a native solution for this, using MenuPopupHelper.setForceShowIcon(true).
private void createMenu(int menuRes, View anchor, MenuBuilder.Callback callback) {
Context context = anchor.getContext();
NavigationMenu navigationMenu = new NavigationMenu(context);
navigationMenu.setCallback(callback);
SupportMenuInflater supportMenuInflater = new SupportMenuInflater(context);
supportMenuInflater.inflate(menuRes, navigationMenu);
MenuPopupHelper menuPopupHelper = new MenuPopupHelper(context, navigationMenu, anchor);
menuPopupHelper.setForceShowIcon(true);
menuPopupHelper.show();
}
Usage
private void initMenu(View view) {
view.findViewById(R.id.myButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createMenu(R.menu.help_menu, view, new MenuBuilder.Callback() {
#Override
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
switch (item.getItemId()) {
case R.id.id1:
// Do something
break;
case R.id.id2:
// Do something
break;
case R.id.id3:
// Do something
break;
}
return true;
}
#Override
public void onMenuModeChange(MenuBuilder menu) {
}
});
}
});
}

Along the line of using reflection and without the need to use MenuPopupHelper, you can add
if (popup.getMenu() instanceof MenuBuilder) {
//noinspection RestrictedApi
((MenuBuilder) popup.getMenu()).setOptionalIconsVisible(true);
}
prior to inflating the menu

PopupMenu will not display icons. You can use an ActionBar.
http://developer.android.com/guide/topics/ui/actionbar.html

Some of the solutions above will work with the reflection hack,
Just sharing this: I've recently came across the same issues, but I also wanted to create a more customized thing (adding custom view in the menu) so I created the following lib.
https://github.com/shehabic/Droppy

If you're using AndroidX, which changed the visibility of MenuPopupHelper to package-private, you can avoid the cost of reflection by creating a wrapper class with the same package name.
This exposes package-private members to public.
package androidx.appcompat.widget // Create this package in your project's /src/main/java
import android.annotation.SuppressLint
class PopupMenuWrapper(val t: PopupMenu) {
#SuppressLint("RestrictedApi")
fun setForceShowIcon(show: Boolean) { // Public method
t.mPopup.setForceShowIcon(show)
}
}
fun PopupMenu.wrap() = PopupMenuWrapper(this)
Then call the hidden function as you normally would.
val popup = PopupMenu(anchor.context, anchor)
popup.wrap().setForceShowIcon(true)
popup.show()

If you want to prevent using RestrictedApi use this extention function:
fun PopupMenu.forcePopUpMenuToShowIcons() {
try {
val method = menu.javaClass.getDeclaredMethod(
"setOptionalIconsVisible",
Boolean::class.javaPrimitiveType
)
method.isAccessible = true
method.invoke(menu, true)
} catch (e: Exception) {
e.printStackTrace()
}
}

You can use the setForceShowIcon (true)
PopupMenu(context, view).apply {
setForceShowIcon(true)
menuInflater.inflate(R.menu.menu_edit_professional_experience, menu)
setOnMenuItemClickListener { item ->
Toast.makeText(view.context, "YOU clcick", Toast.LENGTH_LONG).show()
true
}
}.show()
Use setForceShowIcon(true)

The PopupMenu cannot be fully customized. Below you find a general solution to make your PopupMenu customizable via a custom layout. Having that, you can experiment a lot more with different layouts. Cheers.
1 - The Custom PopupMenu class:
public class PopupMenuCustomLayout {
private PopupMenuCustomOnClickListener onClickListener;
private Context context;
private PopupWindow popupWindow;
private int rLayoutId;
private View popupView;
public PopupMenuCustomLayout(Context context, int rLayoutId, PopupMenuCustomOnClickListener onClickListener) {
this.context = context;
this.onClickListener = onClickListener;
this.rLayoutId = rLayoutId;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
popupView = inflater.inflate(rLayoutId, null);
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true;
popupWindow = new PopupWindow(popupView, width, height, focusable);
popupWindow.setElevation(10);
LinearLayout linearLayout = (LinearLayout) popupView;
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
v.setOnClickListener( v1 -> { onClickListener.onClick( v1.getId()); popupWindow.dismiss(); });
}
}
public void setAnimationStyle( int animationStyle) {
popupWindow.setAnimationStyle(animationStyle);
}
public void show() {
popupWindow.showAtLocation( popupView, Gravity.CENTER, 0, 0);
}
public void show( View anchorView, int gravity, int offsetX, int offsetY) {
popupWindow.showAsDropDown( anchorView, 0, -2 * (anchorView.getHeight()));
}
public interface PopupMenuCustomOnClickListener {
public void onClick(int menuItemId);
}
}
2 - Your custom layout, e.g. linearlayout with horizontal layout. In this case I use a simple LinearLayout with TextView items. You can use Buttons, etc.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal">
<TextView
android:id="#+id/popup_menu_custom_item_a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="A"
android:textAppearance="?android:textAppearanceMedium" />
<TextView
android:id="#+id/popup_menu_custom_item_b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="B"
android:textAppearance="?android:textAppearanceMedium" />
// ...
</LinearLayout>
3 - Using the Custom PopupMenu like the normal PopupMenu.
PopupMenuCustomLayout popupMenu = new PopupMenuCustomLayout(
MainActivity.mainActivity, R.layout.popup_menu_custom_layout,
new PopupMenuCustomLayout.PopupMenuCustomOnClickListener() {
#Override
public void onClick(int itemId) {
// log statement: "Clicked on: " + itemId
switch (itemId) {
case R.id.popup_menu_custom_item_a:
// log statement: "Item A was clicked!"
break;
}
}
});
// Method 1: popupMenu.show();
// Method 2: via an anchor view:
popupMenu.show( anchorView, Gravity.CENTER, 0, 0);

Related

How to disable onTouch of other items in Recyclerview? [duplicate]

I am using Floating Action Button. I want to disable Recyclerview Items from Clicking when i press FAB button. I tried this method but not working setClickable(true);
My Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fab="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#fff"
tools:context="com.hartwintech.socialchat.activity.IconTabsActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
</android.support.v7.widget.RecyclerView>
<com.github.clans.fab.FloatingActionMenu
android:id="#+id/floatmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="60dp"
android:layout_marginRight="16dp"
fab:fab_showAnimation="#anim/show_from_bottom"
fab:fab_hideAnimation="#anim/hide_to_bottom"
fab:menu_labels_style="#style/MenuLabelsStyle"
fab:menu_shadowColor="#444"
fab:menu_colorNormal="#FFB805"
fab:menu_colorPressed="#F2AB00"
fab:menu_colorRipple="#D99200"/>
</RelativeLayout>
Java Class
floatMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
#Override
public void onMenuToggle(boolean opened) {
if (opened) {
final int color = R.color.transp;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mrecyclerview.setClickable(false);
mrecyclerview.setEnabled(false);
mrecyclerview.setForeground(new ColorDrawable(ContextCompat.getColor(getContext(), color)));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mrecyclerview.setClickable(true);
mrecyclerview.setEnabled(true);
mrecyclerview.setForeground(null);
}
}
}
});
You can add a simple boolean to your adapter like this:
public boolean isClickable = true;
and set it in your fab-click:
mAdapter.isClickable = true/false;
And within your OnClickListener in the Adapter, only act when it is clickable:
public void onClick(View view) {
if(!isClickable)
return;
// do your click stuff
}
To disable RecyclerView, follow below steps:
1. Add following view into your layout file,
<View
android:id="#+id/viewDisableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#40000000"
android:clickable="true"
android:focusable="true"
android:visibility="gone"/>
2. Set View Visibility `View.VISIBLE when you want to disable RecyclerView else
You can simply use recursion to disable/enable clicks on view
public static void setClickable(View view, boolean clickable) {
if (view != null) {
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
setClickable(viewGroup.getChildAt(i), clickable);
}
}
view.setClickable(clickable);
}
}
Björn Kechel's answer helps me. As he said I just added Boolean. When i click the fab menu the boolean is activated. Then have to write the condition on mrecyclerview.addOnItemTouchListenerJava Class
public Boolean fabClick = false;
floatMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
#Override
public void onMenuToggle(boolean opened) {
if (opened) {
final int color = R.color.transp;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
fabClick = true;
mrecyclerview.setClickable(false);
mrecyclerview.setEnabled(false);
mrecyclerview.setForeground(new ColorDrawable(ContextCompat.getColor(getContext(), color)));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
fabClick = false;
mrecyclerview.setClickable(true);
mrecyclerview.setEnabled(true);
mrecyclerview.setForeground(null);
}
}
}
});
mrecyclerview.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mrecyclerview, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
if(!fabClick) {
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.fragment_anim_start, R.anim.fragment_anim_stop);
Intent i = new Intent(getActivity(), Group_Chat_Screen.class);
startActivity(i);
}
}
You need to set the click listener to every FloatingActionButton.
see this issue on library
Working solution with RecyclerView.OnItemTouchListener:
#SuppressLint("ClickableViewAccessibility")
#BindingAdapter("itemsClickable")
fun setRecyclerViewClickable(view: RecyclerView, clickable: Boolean) {
view.isEnabled = clickable
if (!clickable) {
val itemTouchListener = object : RecyclerView.OnItemTouchListener {
override fun onTouchEvent(rv: RecyclerView?, e: MotionEvent?) {
}
override fun onInterceptTouchEvent(rv: RecyclerView?, e: MotionEvent?): Boolean {
return rv?.isEnabled == false
}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
}
}
view.addOnItemTouchListener(itemTouchListener)
view.tag = itemTouchListener
} else {
(view.tag as? RecyclerView.OnItemTouchListener)?.let {
view.requestDisallowInterceptTouchEvent(true)
view.removeOnItemTouchListener(it)
}
}
}
Java
recyclerView.setOnTouchListener((view1, motionEvent) -> true );
Kotlin
reyclerView.setOnTouchListener { v, event -> true }
this solution disables all touch events
You can disable the touch of recyclerview
recyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
In the xml file, set the layout_width and layout_height for FloatingActionMenu as match_parent and set clickable as false :
android:layout_width="match_parent "
android:layout_height="match_parent "
android:clickable="false"
In your java class,
floatMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
#Override
public void onMenuToggle(boolean opened) {
if (opened) {
floatMenu.setClickable(true);
} else {
floatMenu.setClickable(false);
}
}
});
This should work.
I solved this problem with very simple logic. This will prevent double click on single item and multiple items of RecyclerView as well.
Declare a Variable in your Activity.
private long mLastClickTime = 0;
Then use in any OnClickListener.
#Override
public void onClick(View v) {
if(SystemClock.elapsedRealtime() - mLastClickTime < 1000){//You can reclick after 1 second
return;//Before 1 seconds from first click this onclick will return from here
}
mLastClickTime = SystemClock.elapsedRealtime();
//Do stuff here
}
Actually I found this solution in stackover flow when I was searching for preventing double click on Button. I'm writing this line to acknowledge that actual answer is posted by someone ( Unfortunatly I'm unable to find that answer to link his/her answer here.)
Hope this will solve your problem.:)

How to make a horizontal ContextMenu?

I have made an Activity called Accounts and I want to add a horizontal ContextMenu. This may look like the cut, copy and paste options. Is there any way to add this horizontal custom menu onLongClick on the list items?
Here's what I've got so far.
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
LayoutInflater inflater = getLayoutInflater().from(this);
View view = inflater.inflate(R.layout.custom_listview, null, false);
menu.setHeaderView(view);
menu.add("Delete");
menu.add("Edit");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
View v = listView.getChildAt(position);
TextView typeTv = v.findViewById(R.id.custom_listview_type);
TextView userTv = v.findViewById(R.id.custom_listview_user);
TextView passTv = v.findViewById(R.id.custom_listview_password);
if (item.getTitle().equals("Delete")) {
db.execSQL("delete from user_added_accounts where accountType = '" + typeTv.getText().toString() + "' and username = '" + userTv.getText().toString() + "';");
recreate();
}
if (item.getTitle().equals("Edit")) {
update(typeTv.getText().toString(), userTv.getText().toString(), passTv.getText().toString());
}
return true;
}
And the current UI looks like this.
Here is something like I want,
Simply you can achieve by QuickAction library.
https://github.com/piruin/quickaction
https://github.com/lorensiuswlt/NewQuickAction
Hope this will help you!!
I think the thing you need is the PopupWindow. Its easier to implement and has its custom layout setting option. The PopupWindow can be set in custom position as you wish and the idea of implementing a sample copy/paste UI that you are thinking of, can be served with the implementation of PopupWindow as well.
I found this answer very informative if you want to implement your situation with PopupWindow instead of implementing it with context menu.
In the above answer that I mentioned and provided a like to, has a PopupWindow which has a TextView only. You might implement any custom/complex UI instead of having a simple TextView like its shown there.
I hope that helps.
Update
As asked in the comment that getting locations of the position of PopupWindow can be set dynamically as well. I am referring to another link, so that you can check the implementation from there as well.
Here's the implementation of using PopupWindow in a list.
So , I wrote below code few year back. You need to make two class first is PopUp and second is TringleView.
PopUp :- Make dialog box and open into near your view(where you want
to open dialog). You can change popup bg color.
TringleView :- Make tringle view or you can say pointed arrow.You can change pointed arrow bg color.
View contentView = ((FragmentActivity)v.getContext()).getLayoutInflater().inflate(R.layout.edit_delete_layout,getAttachedRecyclerView(),false);
// this view denote where you click or you want to open dialog near
PopUp.showPopupOnView(((FragmentActivity) v.getContext()).getSupportFragmentManager(),contentView,view,false);
PopUp.class
public class PopUp extends DialogFragment {
protected int targetX;
protected int targetY;
protected int targetWidth;
protected int targetHeight;
protected Bitmap targetViewImage;
protected View contentView;
private SmartWorksPopUpViewHolder fragmentViewHolder;
private static int bgDrawable = R.drawable.round_corner_white_bg;
protected static int ONE_DIP;
private static int arrowBgColor = R.color.border_color;
private static int arrowWidthMultiple = 25;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ONE_DIP == 0) {
ONE_DIP = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 1, getResources()
.getDisplayMetrics());
}
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Translucent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
AbsoluteLayout parent = new AbsoluteLayout(getActivity());
parent.setId(R.id.parentLayout);
return parent;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.fragmentViewHolder = createViewHolder(view);
bindView(fragmentViewHolder);
}
protected SmartWorksPopUpViewHolder createViewHolder(
View fragmentView) {
return new SmartWorksPopUpViewHolder(fragmentView, contentView);
}
private void bindView(SmartWorksPopUpViewHolder vh) {
if (fragmentViewHolder != null) {
setupTargetDummyView(vh);
boolean showOnTop = shouldShowOnTop();
setupArrow(vh, showOnTop);
setupContent(vh, showOnTop);
}
}
protected void setupContent(SmartWorksPopUpViewHolder vh, boolean showOnTop) {
final int y;
AbsoluteLayout.LayoutParams arrowParams = (android.widget.AbsoluteLayout.LayoutParams) vh.arrow
.getLayoutParams();
int measureHeight = View.MeasureSpec.makeMeasureSpec(
ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
int measureWidth = View.MeasureSpec.makeMeasureSpec(
getActivity().getWindow().getDecorView().getWidth(), View.MeasureSpec.EXACTLY);
vh.popupView.measure(measureWidth, measureHeight);
if (showOnTop) {
y = this.targetY - vh.popupView.getMeasuredHeight() + ONE_DIP;
} else {
y = arrowParams.y + arrowParams.height - ONE_DIP * 2;
}
updateAbsoluteLayoutParams(
getActivity().getResources().getDimensionPixelOffset(R.dimen.sixty_dp),
y,
getActivity().getWindow().getDecorView().getWidth() -
getActivity().getResources().getDimensionPixelOffset(R.dimen.seventy_dp),
ViewGroup.LayoutParams.WRAP_CONTENT, vh.popupView);
vh.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exit();
}
});
}
private void setupArrow(SmartWorksPopUpViewHolder vh, boolean showOnTop) {
final int arrowHeight = 15 * ONE_DIP;
final int arrowWidth = arrowWidthMultiple * ONE_DIP;
vh.arrow.setDirectionAndColor(showOnTop ? "down" : "top", vh.popupView.getContext().getResources().getColor(arrowBgColor));
final int x = (int) (targetX + targetWidth / 3 - arrowWidth / 2);
final int y = targetY + (showOnTop ? -arrowHeight : targetHeight);
updateAbsoluteLayoutParams(x, y, arrowWidth, arrowHeight, vh.arrow);
}
private void setupTargetDummyView(SmartWorksPopUpViewHolder vh) {
vh.targetViewDummy.setImageBitmap(targetViewImage);
updateAbsoluteLayoutParams(targetX, targetY, targetWidth, targetHeight, vh.targetViewDummy);
}
protected void updateAbsoluteLayoutParams(int x, int y, int width, int height, View view) {
AbsoluteLayout.LayoutParams layoutParams =
(android.widget.AbsoluteLayout.LayoutParams) view.getLayoutParams();
layoutParams.x = x;
layoutParams.y = y;
layoutParams.height = height;
layoutParams.width = width;
view.setLayoutParams(layoutParams);
}
private boolean shouldShowOnTop() {
int windowHeight = getActivity().getWindow().getDecorView().getHeight();
int windowMid = windowHeight / 4;
return targetY > windowMid;
}
#Override
public void onDestroyView() {
this.fragmentViewHolder = null;
super.onDestroyView();
}
protected static class SmartWorksPopUpViewHolder {
protected AbsoluteLayout parent;
protected View popupView;
protected TringleView arrow;
protected AppCompatImageView targetViewDummy;
protected SmartWorksPopUpViewHolder(View fragmentView, View content) {
this.parent = (AbsoluteLayout) fragmentView;
final Context mContext = fragmentView.getContext();
this.popupView = content;
this.arrow = new TringleView(mContext);
this.targetViewDummy = new SmartWorksAppCompactImageView(mContext);
this.parent.addView(popupView);
this.parent.addView(arrow);
this.parent.addView(targetViewDummy);
this.parent.setBackgroundColor(0x00000000);
content.setBackgroundResource(bgDrawable);
}
}
public static PopUp showPopupOnView(FragmentManager fm, View contentView, View targetView, boolean showTargetView) {
int[] location = new int[2];
targetView.getLocationInWindow(location);
PopUp fragment = new PopUp();
fragment.targetX = location[0];
fragment.targetY = (int) (location[1] - TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25,
targetView.getResources().getDisplayMetrics()));
fragment.targetWidth = targetView.getMeasuredWidth();
fragment.targetHeight = targetView.getMeasuredHeight();
fragment.contentView = contentView;
fragment.show(fm, "offer");
return fragment;
}
public void exit() {
dismiss();
}
public static void setArrowBackgroundColor(int color) {
arrowBgColor = color;
}
public static void setArrowWidthMultiple(int arrowWidth) {
arrowWidthMultiple = arrowWidth;
}
}
TringleView.class
public class TringleView extends View {
private String direction;
private int color;
public TringleView(Context context) {
super(context);
setDirectionAndColor("right", Color.RED);
}
public TringleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setDirectionAndColor(attrs.getAttributeValue(null, "direction"), Color.RED);
}
public TringleView(Context context, AttributeSet attrs) {
super(context, attrs);
setDirectionAndColor(attrs.getAttributeValue(null, "direction"), Color.RED);
}
public void setDirectionAndColor(String direction, int color) {
if (direction != null && !direction.equals(this.direction) || this.color != color) {
createTriangleDrawable(direction, color);
}
}
private void createTriangleDrawable(String string, int color) {
int width = MeasureSpec.makeMeasureSpec(30, MeasureSpec.UNSPECIFIED);
int height = MeasureSpec.makeMeasureSpec(20, MeasureSpec.UNSPECIFIED);
Path path = new Path();
if (string == null) {
string = "right";
}
if (string.equals("top")) {
path.moveTo(0, height);
path.lineTo(width / 2, 0);
path.lineTo(width, height);
} else if (string.equals("left")) {
path.moveTo(width, 0);
path.lineTo(0, height / 2);
path.lineTo(width, height);
} else if (string.equals("right")) {
path.moveTo(0, 0);
path.lineTo(width, height / 2);
path.lineTo(0, height);
} else if (string.equals("down")) {
path.moveTo(0, 0);
path.lineTo(width / 2, height);
path.lineTo(width, 0);
}
path.close();
ShapeDrawable shapeDrawable = new ShapeDrawable(new PathShape(path, width, height));
shapeDrawable.getPaint().setColor(color);
setBackground(shapeDrawable);
this.color = color;
this.direction = string;
}
}
edit_delete_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
app:cardCornerRadius="#dimen/five_dp"
android:layout_margin="#dimen/ten_dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:gravity="center"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/share"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:visibility="visible"
android:gravity="center"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp"
android:text="Share"
android:layout_weight="1"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:background="#color/grey_unselect"
android:layout_height="match_parent" />
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/reportSpam"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:visibility="visible"
android:gravity="center"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp"
android:text="Spam"
android:layout_weight="1"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:background="#color/grey_unselect"
android:layout_height="match_parent" />
<!--<View-->
<!--android:layout_width="match_parent"-->
<!--android:layout_marginLeft="#dimen/three_dp"-->
<!--android:layout_marginRight="#dimen/three_dp"-->
<!--android:background="#color/white"-->
<!--android:layout_height="#dimen/one_dp" />-->
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/edit"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:gravity="center"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp"
app:swFontName="robotoNormal"
android:layout_weight="1"
android:text="#string/edit"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:background="#color/grey_unselect"
android:layout_height="match_parent" />
<!--<View-->
<!--android:layout_width="match_parent"-->
<!--android:layout_marginLeft="#dimen/three_dp"-->
<!--android:layout_marginRight="#dimen/three_dp"-->
<!--android:background="#color/white"-->
<!--android:layout_height="#dimen/one_dp" />-->
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/delete"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:gravity="center"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp" android:layout_weight="1"
android:text="#string/delete"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:background="#color/grey_unselect"
android:layout_height="match_parent" />
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/cancel"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:gravity="center"
android:layout_weight="1"
android:visibility="visible"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp"
android:textStyle="bold"
android:text="#string/select_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
Result
So if you want to make view as horizontal then you need to make horizontal layout according to your requirement. So can do this task to change your edit_delete_layout.xml which your putting into contentView then pass to Popup class method.
Note:- You can customise popup class according to your requirement and I know this code having so many deprecated view so you can update yourself.
To show compact contextual menu you need to create ActionMode for the Menu, let me show you how:
Suppose your action menu XML have delete, copy and forward actions:
<?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/action_copy"
android:icon="#drawable/ic_vector_menu_copy"
android:title="Copy"
app:showAsAction="always" />
<item
android:id="#+id/action_delete"
android:icon="#drawable/ic_vector_menu_delete"
android:title="Delete"
app:showAsAction="always" />
<item
android:id="#+id/action_forward"
android:icon="#drawable/ic_vector_menu_forward"
android:title="Forward"
app:showAsAction="always" />
</menu>
Create your action menu in your Activity
//Global variable in Activity/Fragment to manage close the menu
private ActionMode mActionMode;
//Action mode callbacks
//Contextual Action bar - for showing delete/copy/... on action bar
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_contextual_action, menu);
return true;
}
// Called each time the action mode is shown.
// Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
//Do the delete action
//mAdapter.resetSelection();
mode.finish(); // Action picked, so close the TAB
//showToast "Deleted successfully"
return true;
case R.id.action_copy:
//mAdapter.resetSelection();
MyClipboardManager.copyToClipboard(ChatDetailActivity.this, mAdapter.getSelectedMessageText());
mode.finish(); // Action picked, so close the TAB
//showToast "Text copied to clipboard"
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
//mAdapter.resetSelection();
}
};
#Override
public void onBackPressed() {
//Closing menu first if it's visible rather than doing the back press action
if (mActionMode != null && mActionMode.getMenu().hasVisibleItems()) {
mActionMode.finish();
return;
}
super.onBackPressed();
}
#Override
public void onDestroy() {
//Closing menu
if (mActionMode != null) {
mActionMode.finish();
}
super.onDestroy();
}
*Set the callback to the global action mode variable
mActionMode = startSupportActionMode(mActionModeCallback);
*Set title to the menu
mActionMode.setTitle("Menu title");
*Invalidate the menu after settings value
mActionMode.invalidate();
Style to manage compact contextual menu
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowDisablePreview">true</item>
<!--CONTEXTUAL action MODE-->
<item name="android:windowContentOverlay">#null</item>
<!--ActionMode background color-->
<!-- <item name="android:actionModeBackground">#color/colorPrimary</item>-->
<!--To Overlay existing toolbar, NOTE We are not using android: to let it work everywhere-->
<item name="windowActionModeOverlay">true</item>
<item name="actionModeStyle">#style/AppActionModeStyle</item>
<item name="android:actionModeCloseDrawable">#drawable/ic_arrow_back_24dp</item>
</style>
<style name="AppActionModeStyle" parent="#style/Widget.AppCompat.ActionMode">
<!--ActionMode background color-->
<item name="background">#color/colorPrimary</item>
<!--ActionMode text title color-->
<item name="titleTextStyle">#style/ActionModeTitleTextStyle</item>
</style>
<style name="ActionModeTitleTextStyle" parent="#style/TextAppearance.AppCompat.Widget.ActionMode.Title">
<item name="android:textColor">#android:color/white</item>
</style>

Change custom SubMenu background color with Java code

In my home activity, I have a toolbar with a custom Overflow menu and I want it to change color to be accorded with toolbar background color (cause toolbar background color can change (user changes to his own favorite color))...I don't know how to do it :
Here's my overflow_menu.xml :
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/overflow_save_current" app:showAsAction="always" android:title="#string/overflow_save_current" android:icon="#drawable/ic_action_save_light" />
<item android:id="#+id/overflow_settings" app:showAsAction="always" android:title="#string/overflow_settings" android:icon="#drawable/ic_action_settings_light" />
<item android:id="#+id/overflow_overflow" app:showAsAction="always" android:icon="#drawable/ic_action_overflow_light">
<menu>
<item android:id="#+id/overflow_feed_back" app:showAsAction="never|withText" android:title="#string/overflow_feed_back" android:icon="#drawable/ic_action_send_now_light" />
<item android:id="#+id/overflow_about_us" app:showAsAction="never|withText" android:title="#string/overflow_about_us" android:icon="#drawable/ic_action_about_light" />
<item android:id="#+id/overflow_exit" app:showAsAction="never|withText" android:title="#string/overflow_exit" android:icon="#drawable/ic_action_forward_light" />
</menu>
</item>
And here's OnPrepareOptionsMenu() method :
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
/* Resources res = getResources();
item = menu.findItem(R.id.overflow_feed_back);
SpannableStringBuilder builder = new SpannableStringBuilder("* " + res.getString(R.string.overflow_feed_back));
builder.setSpan(new ImageSpan(this, android.R.drawable.ic_menu_send), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
item.setTitle(builder); */
if (!Common.compatible(Common.color, 0xFF000000)) {
menu.findItem(R.id.overflow_save_current).setIcon(R.drawable.ic_action_save_dark);
menu.findItem(R.id.overflow_settings).setIcon(R.drawable.ic_action_settings_dark);
menu.findItem(R.id.overflow_overflow).setIcon(R.drawable.ic_action_overflow_dark);
} else {
menu.findItem(R.id.overflow_save_current).setIcon(R.drawable.ic_action_save_light);
menu.findItem(R.id.overflow_settings).setIcon(R.drawable.ic_action_settings_light);
menu.findItem(R.id.overflow_overflow).setIcon(R.drawable.ic_action_overflow_light);
}
return super.onPrepareOptionsMenu(menu);
}
I've already tried to change background color of each element...but I got NPE each time, with menu.findItem(R.id.overflow_about_us).getActionView().setBackgroundColor(Color.BLUE);
Hope you'll find a solution for me, Darkball60
So...no one helped me...so I had to work alone...hours and hours...to finally find the solution :
#Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
// Do you own inflater stuff here
// Check for menu items (Options menu AKA menu key)
if (name.equalsIgnoreCase("android.support.v7.view.menu.ListMenuItemView")) {
try {
// Ask our inflater to create the view
final View view = LayoutInflater.from(context).createView(name, null, attrs);
// Kind of apply our own background
new Handler().post(new Runnable() {
public void run() {
if (!Common.compatible(Common.color, 0xFF000000)) {
try {
((TextView)((RelativeLayout)((ListMenuItemView)view).getChildAt(1)).getChildAt(0)).setTextColor(0xFFFFFFFF);
} catch (ClassCastException e) {
}
} else {
try {
((TextView)((RelativeLayout)((ListMenuItemView)view).getChildAt(1)).getChildAt(0)).setTextColor(0xFF000000);
} catch (ClassCastException e) {
}
}
view.setBackgroundColor(Common.color);
}
});
return view;
} catch (InflateException e) {
} catch (ClassNotFoundException e) {
}
}
return null;
}
If background is dark...so textColor is white...and if background is light, textColor is black.
Below are two screens with different toolbar color :
Hope it helps someone else than me, Darkball60 (and if you like the answer...feel free to upvote :))

How to add long press functionality to navigation drawer items?

As the title says, I'm trying to add long press functionality to items in my app's navigation drawer. These items are added dynamically (not inflated from navigation_drawer_menu.xml), so I can't solve this by specifying some attributes in the xml file.
I've looked at several questions on Stackoverflow, particularly this one: How to set a long click listener on a MenuItem (on a NavigationView)?. I've implemented the setActionView solution, but I end up getting a blank button on the right edge of the nav drawer item. When I long press the text, nothing happens. When I long press the little blank button, I get what I want.
How can I set a OnLongClickListener for the whole menuItem, and not just for its (I'm assuming it's a button) on its right side? Thank you for reading, and if any more info is needed, I'm happy to help you help me:)
I had the same problem and managed to solve it by digging into the NavigationView's view hierarchy.
The first step is to understand the view hierarchy of your NavigationView. You can use the piece of code from this post to print out the NavigationView's view hierarchy.
Then start digging for the view you're targeting. In my case:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Start digging into the view hierarchy until the correct view is found
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
ViewGroup navigationMenuView = (ViewGroup)navigationView.getChildAt(0);
ViewGroup navigationMenuItemView = (ViewGroup)navigationMenuView.getChildAt(2);
View appCompatCheckedTextView = navigationMenuItemView.getChildAt(0);
// Attach click listener
appCompatCheckedTextView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.i("test", "LONG CLICK");
return true;
}
});
return super.onPrepareOptionsMenu(menu);
}
We choose to do these things not because they are easy, but because they are hard. And because my UI would have come unglued if I couldn't do this.
Import the NavigationItemLongPressInterceptor class given below into your project.
Menu items for the NavigationView are declared as normal, with two additional attributes to add long-press behaviour.
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:showIn="navigation_view">
<group android:id="#+id/home_views">
<item
android:id="#+id/nav_item_1"
android:icon="#drawable/ic_item_1"
android:title="Item 1"
android:checkable="true"
app:actionViewClass=
"com.twoplay.netplayer.controls.NavigationItemLongPressInterceptor"
app:showAsAction="always"
/>
<item
android:id="#+id/nav_item_2"
android:icon="#drawable/ic_item_2"
android:title="Item 2"
android:checkable="true"
app:actionViewClass=
"com.twoplay.netplayer.controls.NavigationItemLongPressInterceptor"
app:showAsAction="always"
/>
</group>
</menu>
Add an implementation for NavigationItemLongPressInterceptor.OnNavigationItemLongClickListener to your activity,
and implement the onNavigationItemLongClick method:
public class MainActivity extends MediaActivity
implements
NavigationView.OnNavigationItemSelectedListener,
NavigationItemLongPressInterceptor.OnNavigationItemLongClickListener
. . .
#Override
public void onNavigationItemLongClick(
NavigationItemLongPressInterceptor.SelectedItem selectedItem,
View view)
{
// supply your NavigationView as an argument.
int menItemId = selectedItem.getItemId(mNavigationView);
switch (id) {
...
case R.id.nav_local_device:
case R.id.nav_upnp_devices: {
showNavigationItemSetAsHomePopupMenu(id,view);
}
break;
}
}
}
You probably have to add com.twoplay.netplayer.controls.NavigationItemLongPressInterceptor to your proguard rules.
NavigationItemLongPressInterceptor.java:
package com.twoplay.netplayer.controls;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.Nullable;
/**
* Attach a long-click handler to a menu item in a NavigationView menu.
*
* To handle long-click of a Navigator menu item, declare the item as normal, and append
* app:actionViewClass="com.twoplay.netplayer.controls.NavigationItemLongPressInterceptor" and
* app:showAsAction="always" attributes:
*
* <menu xmlns:tools="http://schemas.android.com/tools"
* xmlns:app="http://schemas.android.com/apk/res-auto"
* >
*
* <group android:id="#+id/home_views">
* <item
* android:id="#+id/nav_item_1"
* android:icon="#drawable/ic_item_1"
* android:title="Item 1"
* android:checkable="true"
* app:actionViewClass=
* "com.twoplay.netplayer.controls.NavigationItemLongPressInterceptor"
* app:showAsAction="always"
* </item>
* </group>
*
* Your Application class must implement <L NavigationItemLongPressInterceptor.OnNavigationItemLongClickListener/>
* in order to receive notification of long pressed menu items.
*
* You can retrieve the item id of the menu by calling <L SelectedItem.getItemId/> on the
* <L SelectedItem/> provided as an argument to <L NavigationItemLongPressInterceptor.onNavigationItemLongClick/>
*
* />
*
*/
#SuppressWarnings("unused")
public class NavigationItemLongPressInterceptor extends View {
public NavigationItemLongPressInterceptor(Context context) {
super(context);
init();
}
public NavigationItemLongPressInterceptor(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public NavigationItemLongPressInterceptor(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init()
{
setVisibility(View.INVISIBLE);
setLayoutParams(new ViewGroup.LayoutParams(0,0));
}
public interface OnNavigationItemLongClickListener {
void onNavigationItemLongClick(SelectedItem itemHandle, View view);
}
public static class SelectedItem {
private final View actionView;
private SelectedItem(View actionView) {
this.actionView = actionView;
}
public int getItemId(NavigationView navigationView)
{
return getItemId(navigationView.getMenu());
}
private int getItemId(Menu menu) {
for (int i = 0; i < menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item.getActionView() == actionView) {
return item.getItemId();
}
SubMenu subMenu = item.getSubMenu();
if (subMenu != null) {
int itemId = getItemId(subMenu);
if (itemId != -1) {
return itemId;
}
}
}
return -1;
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
View parent = getMenuItemParent();
parent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
OnNavigationItemLongClickListener receiver = getReceiver();
if (receiver == null)
{
throw new RuntimeException("Your main activity must implement NavigationViewLongPressInterceptorView.OnNavigationItemLongClickListener");
}
View parent = getMenuItemParent();
receiver.onNavigationItemLongClick(
new SelectedItem(NavigationItemLongPressInterceptor.this),parent);
return true;
}
});
}
private Activity getActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity)context;
}
context = ((ContextWrapper)context).getBaseContext();
}
return null;
}
private OnNavigationItemLongClickListener getReceiver() {
Activity activity = getActivity();
if (activity == null) return null;
if (activity instanceof OnNavigationItemLongClickListener)
{
return (OnNavigationItemLongClickListener)activity;
}
return null;
}
private View getMenuItemParent() {
View parent = (View)getParent();
while (true)
{
if (parent.isClickable())
{
return parent;
}
parent = (View) parent.getParent();
}
}
}
This code targets androidx, but it can be trivially backported to AppCompat. Just delete the androidx imports, and replace them with corresponding AppCompat imports. Hopefully older versions of NavigationView lay out actionViews the same way.
Tested with 'androidx.appcompat:appcompat:1.0.2', 'com.google.android.material:material:1.0.0'. I'm reasonably confident that it is version-safe. Let me know if getMenuItemParent()needs adjustments for other AppCompat versions, and I will incorporate changes here.
I had to do similar and went with onItemLongClick
https://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html
my implementation was a little different though as I had an expandable list in the navigation drawer and each item had to have an onClick as well as an onLongClick method call, each item on the navigation drawer was also added dynamically by the user of the app.
listView.setOnItemLongClickListener(new View.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(HomeActivity.this, id +"", Toast.LENGTH_LONG).show();
return true;
}
});

EditText on demand widget

I'd like to have a TextView display text, and when you click/longclick on it, a textbox should "show up" and allow editing of said text. When you're done editing (onkey enter i suppose) it should revert back to a textview with the updated text...
I'm wondering if it's feasable to implement such a widget or should I hack a workaround? Tips and suggestions are very welcome.
If you need further idea of what I mean, just go to your e.g. (windows) skype profile and see for yourself.
EDIT:
Clarification: I'm specifically asking for a widget or such which is a textview until clicked on, then transforms to an edittext containing the same text; once done editing it transforms back to a textview representing the new changed text. Thats what i mean by "edittext on demand widget".
But I'm hoping to get something better than
public class Widget {
TextView text;
EditText edit;
String textToRepresent;
//...
}
You have a few different options here.
First you will have to register an onClick or onLongClick to the TextView that you want to make interactive. Just make sure that the user knows it's clickable
Then have your onClick function start a DialogFragment. I like to create show functions. Note that you can use the support libraries here to make your app backwards compatible.
private void showDialog() {
MyDialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "dialog");
}
The DialogFragment is pretty straight forward. In your onCreateView you'll inflate the View that you'll want to display to the user. You can alternatively wrap it with a simple AlertDialogBuilder if you don't want to go custom.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_dialog_layout);
mTitleEditText = (TextView) view.findViewById(R.id.title);
mTitleEditText.setOnClickListener(this);
return view;
}
After your findViewByIds set your onClickListeners.
The last thing you have to take care of is getting data back into your original TextView.
You can do this by creating a public method in your Activity that you can call from inside of your DialogFragment. Something like this
#Override
public void onClick(View v) {
int clickedId = v.getId();
if (clickedId == mDoneButton.getId()) {
MyActivity activity = (MyActivity)getActivity();
mTitle = mTitleEditText.getText().toString();
activity.setText(mTitle);
dismiss();
}
}
I would recommend using a DialogFragment because it will handle your life cycle nicely.
However, another option would be to create a new Activity themed to be a dialog
<activity android:theme="#android:style/Theme.Dialog" />
Then you can startActivityForResult to display your dialog and then capture your results in onActivityResult
Here is my solution. I just give you the basic one. Create a TextView in front of EditText and two Button OK,Cancel (You can change to ImageButton like Skype). Change the visiblity of two view. The code is so simple without comment. You can add some null checking according your logic.
public class CompoundTextView extends RelativeLayout implements OnClickListener {
private EditText edt;
private TextView txt;
RelativeLayout layout;
public SkypeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
edt = (EditText) findViewById(R.id.edt);
txt = (TextView) findViewById(R.id.txt_name);
layout = (RelativeLayout) findViewById(R.id.layout);
Button ok = (Button) findViewById(R.id.ok_btn);
Button cancel = (Button) findViewById(R.id.cancel_btn);
ok.setOnClickListener(this);
cancel.setOnClickListener(this);
txt.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ok_btn:
String editString = edt.getText().toString();
txt.setText(editString);
layout.setVisibility(View.INVISIBLE);
txt.setVisibility(View.VISIBLE);
break;
case R.id.cancel_btn:
layout.setVisibility(View.INVISIBLE);
txt.setVisibility(View.VISIBLE);
break;
case R.id.txt_name:
txt.setVisibility(View.INVISIBLE);
layout.setVisibility(View.VISIBLE);
break;
}
}
}
Create a XML skypetextview. You can customize font and background to make it's prettier.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/txt_name"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:textColor="#FFFFFF"
android:textSize="14sp"
android:background="#ff0000" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:id="#+id/layout" >
<EditText
android:id="#+id/edt"
android:layout_width="270dp"
android:layout_height="100dp" />
<Button
android:id="#+id/ok_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/edt"
android:text="OK" />
<Button
android:id="#+id/cancel_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ok_btn"
android:layout_toRightOf="#id/edt"
android:text="Cancel" />
</RelativeLayout>
</RelativeLayout>
add (or include) this view to the layout you want.
Example :
public class TestActivity extends Activity {
SkypeTextView test;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflate = getLayoutInflater();
test = (SkypeTextView ) inflate.inflate(R.layout.compound_text_view,
null);
setContentView(test);
}
PS: i forgot. You should add some underline format for your textview in order to make user notice it clickable
Let a EditText change its background based on its state(Editable or Frozen). Set a background selector that does this.
Use this selector xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_focused="true" android:drawable="#android:drawable/edit_text"/>
<item android:drawable="#android:drawable/screen_background_light_transparent"/>
</selector>
Like I said on thursday... Yul was pretty close but not quite close. He did have a general same idea but (theoretically) rushed into code too early ;)
The TextBoxOnDemand code supplied below is production-ready. The idea is similar to what I wanted to avoid in the OP and what Yul suggested, but with optimal implementation (using a ViewSwitcher instead of a RelativeLayout for instance)
I gathered the resources needed for this in the following articles:
Creating custom view from xml
Declaring a custom android UI element using XML
Defining custom attrs
How to pass custom component parameters in java and xml
http://kevindion.com/2011/01/custom-xml-attributes-for-android-widgets/
and decided to post them here because the official Google "training" docs are useless and are either obsolete (deprecated) or do not cover what I needed. I hope you don't mind me claiming my own bounty, but this is the solution I wanted (and expected, ergo the bounty).
I guess the code will have to do ;)
TextBoxOnDemand.java:
package com.skype.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnHoverListener;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.ViewSwitcher;
import com.skype.ref.R;
import com.skype.ref.RemoteKeys;
public class TextBoxOnDemand extends ViewSwitcher implements OnClickListener, OnLongClickListener, OnFocusChangeListener, OnHoverListener,
OnEditorActionListener
{
public static final String LOGTAG = "TextBoxOnDemand";
private View btmGuard;
private ImageButton cancel, accept;
private EditText editor;
private RelativeLayout editorLayout;
private TextView face;
private String hint = new String();
private boolean inEditMode = false; //normally this is in textview mode
private boolean inputReady = false;
private String ourData = new String();
private String prefillData = new String();
private String tag = new String(); //usually tag is empty.
private View topGuard;
private int autoLinkMask;// = Linkify.EMAIL_ADDRESSES; //Linkify.ALL;
private ColorStateList textColor, hintColor = null;
public TextBoxOnDemand(Context context)
{
super(context);
build(context);
setEditable(false); //init
}
public TextBoxOnDemand(Context context, AttributeSet attrs)
{
super(context, attrs);
build(context);
init(context, attrs);
setEditable(false); //init
}
public String getPrefillData()
{
return prefillData;
}
public String getTag()
{
return tag;
}
public String getText()
{
Log.d(LOGTAG, "getText() returning '" + ourData + "'");
return ourData;
}
public boolean hasPrefillData()
{
return prefillData.isEmpty();
}
public boolean isEditable()
{
Log.d(LOGTAG, "isEditable() returning " + inEditMode);
return inEditMode;
}
#Override
public void onClick(View v)
{
Log.d(LOGTAG, "onClick(" + v + ")");
if (inEditMode)
{
if (v.equals(accept))
{
if (editor.getEditableText().length() == 0 || editor.getEditableText().length() > 5)
ourData = editor.getEditableText().toString();
setEditable(false);
} else if (v.equals(cancel))
{
setEditable(false);
}
}
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
// Log.d(LOGTAG, "onEditorAction(" + v + ", " + actionId + ", " + event + ") fired!");
Log.d(LOGTAG, "onEditorAction() fired, inputReady = " + inputReady);
if (editor.getEditableText().length() > 0 && editor.getEditableText().length() < (prefillData.length() + 2)) return true; //the user needs to enter something
if (inputReady && (event.getKeyCode() == RemoteKeys.ENTER.keycode() || event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) //always is
{
if (editor.getEditableText().length() > prefillData.length() || editor.getEditableText().length() == 0)
ourData = editor.getEditableText().toString();
setEditable(false);
return false;
}
if ((editor.getEditableText().toString().compareToIgnoreCase(ourData) == 0 || editor.getEditableText().toString()
.compareToIgnoreCase(prefillData) == 0)
&& !inputReady) //means we didn't just keep on holding enter
return true;
else
inputReady = true;
return true;
}
#Override
public void onFocusChange(View v, boolean hasFocus)
{
Log.d(LOGTAG, "onFocusChange(" + v + ", " + hasFocus + ")\tinEditMode = " + inEditMode);
if (inEditMode)
{
if (hasFocus && (v.equals(topGuard) || v.equals(btmGuard)))
{
setEditable(false);
requestFocus();
}
if (hasFocus && (v.equals(editor) || v.equals(accept) || v.equals(cancel)))
{
//do nothing, you should be able to browse freely here
if (ourData.isEmpty() && editor.getEditableText().length() < prefillData.length())
{
Log.d(LOGTAG, "adding prefill, before = " + editor.getEditableText());
editor.setText("");
editor.append(prefillData);
Log.d(LOGTAG, "now is = " + editor.getEditableText());
}
}
} else
{
String text = (ourData.isEmpty()) ? hint : ourData;
ColorStateList color;
if (hintColor != null && ourData.isEmpty())
color = hintColor;
else
color = textColor;
face.setTextColor(color);
if (hasFocus)
{
SpannableString ss = new SpannableString(text);
ss.setSpan(new UnderlineSpan(), 0, text.length(), 0);
face.setText(ss);
} else
face.setText(text);
}
}
#Override
public boolean onHover(View v, MotionEvent event)
{
// Log.d(LOGTAG, "onHover()");
String text = (ourData.isEmpty()) ? hint : ourData;
ColorStateList color;
if (hintColor != null && ourData.isEmpty())
color = hintColor;
else
color = textColor;
face.setTextColor(color);
switch (event.getAction())
{
case MotionEvent.ACTION_HOVER_ENTER:
SpannableString ss = new SpannableString(text);
ss.setSpan(new UnderlineSpan(), 0, text.length(), 0);
face.setText(ss);
break;
case MotionEvent.ACTION_HOVER_EXIT:
face.setText(text);
break;
}
return true;
}
#Override
public boolean onLongClick(View v)
{
Log.d(LOGTAG, "onLongClick()\tinEditMode = " + inEditMode);
if (!inEditMode) //implies that getDisplayedChild() == 0, meaning the textview
{
setEditable(true);
return true;
} else
return false;
}
public void setEditable(boolean value)
{
Log.d(LOGTAG, "setEditable(" + value + ")");
inEditMode = value;
if (inEditMode)
{
//display the editorLayout
face.setOnLongClickListener(null);
face.setOnHoverListener(null);
face.setOnFocusChangeListener(null); //because of GC.
face.setOnClickListener(null);
face.setVisibility(View.GONE);
setDisplayedChild(1);
editorLayout.setVisibility(View.VISIBLE);
editor.setOnFocusChangeListener(this);
editor.setOnEditorActionListener(this);
cancel.setOnClickListener(this);
accept.setOnClickListener(this);
accept.setOnFocusChangeListener(this);
cancel.setOnFocusChangeListener(this);
} else
{
editor.setOnFocusChangeListener(null);
editor.setOnEditorActionListener(null);
cancel.setOnClickListener(null);
accept.setOnClickListener(null);
accept.setOnFocusChangeListener(null);
cancel.setOnFocusChangeListener(null);
editorLayout.setVisibility(View.GONE);
setDisplayedChild(0);
face.setVisibility(View.VISIBLE);
face.setOnLongClickListener(this);
face.setOnHoverListener(this);
face.setOnFocusChangeListener(this);
face.setOnClickListener(this);
face.setFocusable(true);
face.setFocusableInTouchMode(true);
}
updateViews();
}
#Override
public void setNextFocusDownId(int nextFocusDownId)
{
super.setNextFocusDownId(nextFocusDownId);
face.setNextFocusDownId(nextFocusDownId);
// editor.setNextFocusDownId(nextFocusDownId);
accept.setNextFocusDownId(nextFocusDownId);
cancel.setNextFocusDownId(nextFocusDownId);
}
#Override
public void setNextFocusForwardId(int nextFocusForwardId)
{
super.setNextFocusForwardId(nextFocusForwardId);
face.setNextFocusForwardId(nextFocusForwardId);
editor.setNextFocusForwardId(nextFocusForwardId);
}
#Override
public void setNextFocusLeftId(int nextFocusLeftId)
{
super.setNextFocusLeftId(nextFocusLeftId);
face.setNextFocusLeftId(nextFocusLeftId);
editor.setNextFocusLeftId(nextFocusLeftId);
}
#Override
public void setNextFocusRightId(int nextFocusRightId)
{
super.setNextFocusRightId(nextFocusRightId);
face.setNextFocusRightId(nextFocusRightId);
cancel.setNextFocusRightId(nextFocusRightId);
}
#Override
public void setNextFocusUpId(int nextFocusUpId)
{
super.setNextFocusUpId(nextFocusUpId);
face.setNextFocusUpId(nextFocusUpId);
// editor.setNextFocusUpId(nextFocusUpId);
accept.setNextFocusUpId(nextFocusUpId);
cancel.setNextFocusUpId(nextFocusUpId);
}
public void setPrefillData(String prefillData)
{
this.prefillData = new String(prefillData);
}
public String setTag()
{
return tag;
}
public void setText(String text)
{
Log.d(LOGTAG, "setText(" + text + ")");
ourData = text;
updateViews();
}
private void build(Context context)
{
Log.d(LOGTAG, "build()");
addView(View.inflate(context, R.layout.textboxondemand, null));
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setOnFocusChangeListener(this);
setOnLongClickListener(this);
face = (TextView) findViewById(R.id.TBOD_textview);
editorLayout = (RelativeLayout) findViewById(R.id.TBOD_layout);
editor = (EditText) findViewById(R.id.TBOD_edittext);
accept = (ImageButton) findViewById(R.id.TBOD_accept);
cancel = (ImageButton) findViewById(R.id.TBOD_cancel);
topGuard = (View) findViewById(R.id.TBOD_top);
btmGuard = (View) findViewById(R.id.TBOD_bottom);
face.setFocusable(true);
face.setFocusableInTouchMode(true);
face.setOnLongClickListener(this);
face.setOnHoverListener(this);
face.setOnFocusChangeListener(this);
face.setOnClickListener(this);
editor.setOnFocusChangeListener(this);
editor.setOnEditorActionListener(this);
editor.setHint(hint);
editor.setFocusable(true);
editor.setFocusableInTouchMode(true);
accept.setOnClickListener(this);
accept.setOnFocusChangeListener(this);
accept.setFocusable(true);
cancel.setFocusable(true);
cancel.setOnFocusChangeListener(this);
cancel.setOnClickListener(this);
topGuard.setFocusable(true);
topGuard.setOnFocusChangeListener(this);
btmGuard.setFocusable(true);
btmGuard.setOnFocusChangeListener(this);
editor.setNextFocusRightId(R.id.TBOD_accept);
editor.setNextFocusDownId(R.id.TBOD_bottom);
editor.setNextFocusUpId(R.id.TBOD_top);
accept.setNextFocusLeftId(R.id.TBOD_edittext);
accept.setNextFocusRightId(R.id.TBOD_cancel);
cancel.setNextFocusLeftId(R.id.TBOD_accept);
}
private void init(Context context, AttributeSet attrs)
{
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextBoxOnDemand);
//Use a
Log.d(LOGTAG, "init()");
if (a == null) Log.d(LOGTAG, "Did you include 'xmlns:app=\"http://schemas.android.com/apk/res-auto\"' in your root layout?");
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i)
{
int attr = a.getIndex(i);
switch (attr)
{
case R.styleable.TextBoxOnDemand_android_hint:
hint = new String(a.getString(attr));
editor.setHint(a.getString(attr));
break;
case R.styleable.TextBoxOnDemand_android_text:
ourData = new String(a.getString(attr));
break;
case R.styleable.TextBoxOnDemand_android_inputType:
int inputType = a.getInt(attr, -1);
if (inputType != -1) editor.setInputType(inputType);
break;
case R.styleable.TextBoxOnDemand_android_textColor:
textColor = a.getColorStateList(attr);
face.setTextColor(textColor);
break;
case R.styleable.TextBoxOnDemand_android_linksClickable:
face.setLinksClickable(a.getBoolean(attr, true));
break;
case R.styleable.TextBoxOnDemand_android_textColorHint:
hintColor = a.getColorStateList(attr);
break;
case R.styleable.TextBoxOnDemand_android_autoLink:
autoLinkMask = a.getInt(attr, 0);
face.setAutoLinkMask(autoLinkMask);
break;
default:
Log.d(LOGTAG, "Skipping attribute " + attr);
}
}
//Don't forget this
a.recycle();
}
private void updateViews()
{
Log.d(LOGTAG, "updateViews()");
// if (getDisplayedChild() == 0) //first child - textview
if (!inEditMode) //first child - textview
{
if (ourData.isEmpty())
{
if (hintColor != null) face.setTextColor(hintColor);
face.setText(hint);
} else
{
face.setTextColor(textColor);
face.setText(ourData);
}
face.setFocusable(true);
face.setFocusableInTouchMode(true);
face.setAutoLinkMask(autoLinkMask);
} else
{ //second child - edittext
editor.setFocusable(true);
editor.setFocusableInTouchMode(true);
if (ourData.startsWith(prefillData) || ourData.length() >= prefillData.length())
editor.setText("");
else
editor.setText(prefillData);
editor.append(ourData);
inputReady = false;
editor.requestFocus();
}
}
public void setAutoLinkMask(LinkifyEnum linkifyEnumConstant)
{
switch (linkifyEnumConstant)
{
case ALL:
autoLinkMask = Linkify.ALL;
break;
case EMAIL_ADDRESSES:
autoLinkMask = Linkify.EMAIL_ADDRESSES;
break;
case MAP_ADDRESSES:
autoLinkMask = Linkify.MAP_ADDRESSES;
break;
case PHONE_NUMBERS:
autoLinkMask = Linkify.PHONE_NUMBERS;
break;
case WEB_URLS:
autoLinkMask = Linkify.WEB_URLS;
break;
case NONE:
default:
autoLinkMask = 0;
break;
}
//set it now
face.setAutoLinkMask(autoLinkMask);
}
public enum LinkifyEnum
{
ALL, EMAIL_ADDRESSES, MAP_ADDRESSES, PHONE_NUMBERS, WEB_URLS, NONE
};
}
I'm still working out some focus-related issues but this works as intended. When I use onFocuslistener 1, you can't focus from one TextBox to the other; when the textbox itself is focusable, I can focus from one to the other just fine, but I cannot inter-focus thru children and thus can't focus on the edittext to type.
the XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/TBOD_textview"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:autoLink="email"
android:focusable="true"
android:focusableInTouchMode="true"
android:linksClickable="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
<RelativeLayout
android:id="#+id/TBOD_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/TBOD_edittext"
android:layout_width="300dp"
android:layout_height="30dp"
android:layout_below="#+id/TBOD_textview"
android:focusable="true"
android:focusableInTouchMode="true"
android:imeOptions="actionDone"
android:inputType="none"
android:maxLines="1"
android:padding="2dp"
android:singleLine="true"
android:textColor="#android:color/black"
android:textSize="14dp" />
<ImageButton
android:id="#+id/TBOD_accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/TBOD_edittext"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/TBOD_edittext"
android:background="#drawable/button_accept_selector" />
<ImageButton
android:id="#+id/TBOD_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/TBOD_edittext"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/TBOD_accept"
android:background="#drawable/button_cancel_selector" />
<View
android:id="#+id/TBOD_top"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:background="#android:color/transparent" />
<View
android:id="#+id/TBOD_bottom"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_alignParentBottom="true"
android:background="#android:color/transparent" />
</RelativeLayout>
</RelativeLayout>
and finally, the attrs.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextBoxOnDemand">
<attr name="android:text" />
<attr name="android:inputType" />
<attr name="android:hint" />
<attr name="android:textColor" />
<attr name="android:textColorHint" />
<attr name="android:linksClickable" />
<attr name="android:autoLink" />
</declare-styleable>
</resources>
This is how I used it in my main xml (after including the required namespace add):
<com.shark.widget.TextBoxOnDemand
android:id="#+id/profile_email2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/profile_skypename"
android:layout_below="#+id/profile_email_placeholder"
android:hint="#string/add_email"
android:inputType="textEmailAddress"
android:textColor="#android:color/white"
android:textColorHint="#color/skype_blue" />
EDIT: I've debugged the focus issues. It turns out that giving focus to children is difficult unless you call
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
Which kinda remedies the issue but still doesn't solve it. After some while of playing around with the onFocusChange() listener still trying to get the perfect behaviour, I threw in the towel and put in added two focus guards. I realized I cannot track the loss of focus only on my container (due to it never receiving focus) but I might as well track the idea of wanting to move away from the edit field... So i went the dirty route and added two invisible bar-like views to sandwitch the edittext in between. Once they got the focus, I could hide the component and ensure they transition properly.
And there it is, now it works as it should. Thanks to all who participated.
EDIT3: final polished version, i dumped the custom tags because they simply don't work reliably enough. Lesson to be learned: if there is an android tag for something, don't bother cloning it.

Categories