Skip to content

Instantly share code, notes, and snippets.

@scruffyfox
Last active April 25, 2020 18:45
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save scruffyfox/3894926 to your computer and use it in GitHub Desktop.
Save scruffyfox/3894926 to your computer and use it in GitHub Desktop.
Image view with long press hint
package in.lib.view;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.Toast;
/**
* Extended image view to show the content description in a Toast view when
* the user long presses.
*
* Note: `android:contentDescription` must be set in order for the toast to
* work
*
* @author Callum Taylor <http://callumtaylor.net>
*/
public class HintedImageButton extends ImageButton implements OnLongClickListener
{
private OnLongClickListener mOnLongClickListener;
public HintedImageButton(Context context)
{
super(context);
setOnLongClickListener(this);
}
public HintedImageButton(Context context, AttributeSet attrs)
{
super(context, attrs);
setOnLongClickListener(this);
}
@Override public void setOnLongClickListener(OnLongClickListener l)
{
if (l == this)
{
super.setOnLongClickListener(l);
return;
}
mOnLongClickListener = l;
}
@Override public boolean onLongClick(View v)
{
if (mOnLongClickListener != null)
{
if (!mOnLongClickListener.onLongClick(v))
{
handleLongClick();
return true;
}
}
else
{
handleLongClick();
return true;
}
return false;
}
private void handleLongClick()
{
String contentDesc = getContentDescription().toString();
if (!TextUtils.isEmpty(contentDesc))
{
int[] pos = new int[2];
getLocationInWindow(pos);
Toast t = Toast.makeText(getContext(), contentDesc, Toast.LENGTH_LONG);
t.setGravity(Gravity.TOP | Gravity.LEFT, pos[0] - ((contentDesc.length() / 2) * 12), pos[1] - 128);
t.show();
}
}
}
@avikalp121
Copy link

i have just started using android studio and in which activity should i paste this code ?
plz reply ASAP

@hendrawd
Copy link

in this line Toast t = Toast.makeText(getContext(), contentDesc, 1200); shouldn't 1200 replaced with Toast.LENGTH_LONG
or Toast.LENGTH_SHORT instead?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment