Android ImageButton swap resource leaves 'residue' - java

I have 2 Images:
IMG_1:
IMG_1_PRESSED:
I display IMG_1 by default, but when I click on it, the image should change to IMG_1_PRESSED.
Here's a code snippet of the button itself, where be is an enum containing the correct drawables:
ImageButton ib = new ImageButton(this.context);
ib.setImageResource(be.getDrawable());
ib.setScaleType(ImageButton.ScaleType.CENTER_INSIDE);
ib.setBackgroundColor(Color.TRANSPARENT);
ib.setPadding(0, 0, 0, 0);
ib.setAdjustViewBounds(true);
ib.setMaxWidth(width);
ib.setMaxHeight(height);
setStrengthListener(ib, be);
And here is the setStrengthListener method:
private void setStrengthListener(final ImageButton ib, final ButtonEnum be){
ib.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
ib.setImageResource(be.getDrawablePressed());
return true;
case MotionEvent.ACTION_UP:
ib.setImageResource(be.getDrawable());
return true;
}
return false;
}
});
}
Now both images are 480x240 and width and height are set to device's width/3 and device's width/6 respectively (I want to display 3 images, hence the /3).
Here's the problem, if the button is pressed, I get this:
There's this little line under the pressed button... I've tried a lot to fix this but somehow that little line has made itself my greatest enemy today.
As an extra effort: the line doesn't show anymore if I set the original resource to IMG_1_PRESSED:
ImageButton ib = new ImageButton(this.context);
ib.setImageResource(be.getDrawablePressed());
ib.setScaleType(ImageButton.ScaleType.CENTER_INSIDE);
ib.setBackgroundColor(Color.TRANSPARENT);
ib.setPadding(0, 0, 0, 0);
....etc
But obviously I don't want to start with a pressed button.
So dear Android experts, what am I doing wrong here?

This is the simplest solution as i know,
Try this
create Xml inside your Drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/btn_pressed_img"android:state_pressed="true" />
<item android:drawable="#drawable/btn_normal_image" />
</selector>
Then add this drawable file as background to your View
Example :
<ImageView
android:id="#+id/enter_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxHeight="100dip"
android:maxWidth="100dip"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:background="#drawable/enter_btn" />
or in Java code
yourView.setImageResource(R.drawable.*drawablefile*);
You can use ImageButton also but ImageView would look better than ImageButton since it doesn't have button borders.

So after a hell of a lot of trial and error, I managed to get that grey line away. In the end it was very simple really, though I'm not completely sure why this fixed it:
The main layout:
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setGravity(Gravity.TOP);
The view creation (layout for imageview is unchanged):
ImageView iv = tbb.getTopBarButton(ButtonEnum.IMG_1);
LinearLayout iViewLayout = new LinearLayout(this);
iViewLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
iViewLayout.setOrientation(LinearLayout.HORIZONTAL);
iViewLayout.addView(iv);
ll.addView(iViewLayout);
Adding a separate layout per imageview seemed to remove the grey line. Would love to know WHY this works though, but for future reference, at least I hope to help others.

Related

How to animate an ImageView from left to fill the screen?

I have an image set in an ImageView and I want to animate it such a way that initially nothing is displayed on the screen and the the image enters from left and go towards right and finally fill the screen
In the code that i examine the image enters from left but doesn't fill the screen and left blank behind itself
ObjectAnimator transAnimation=
ObjectAnimator.ofFloat(imageView,"translationX",-100,100);
transAnimation.setDuration(3000);//set duration
transAnimation.start();//start animation
The code for animation that you posted seems to be working fine. The problem that you have is with imageview itself and the place it takes over your screen.
You said that your imageview is not taking full space and leaving blank space behind it,
so to fix it simply make your imageview width = match_parent. and if it still doesn't work then add scaleType=centerCrop
UPDATE:
Add this code to your onCreate()
imageView.post(new Runnable() {
#Override
public void run() {
startImageAnimation();
}
});
private void startImageAnimation() {
ObjectAnimator animation = ObjectAnimator.ofFloat(imageView, "translationX",-(imageView.getWidth()), 0);
animation.setDuration(1100);
animation.start();
}
step 1: create below left_to_right_anim file in anim directory of res
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="#android:anim/linear_interpolator"
android:fillAfter="true">
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>
step 2:
//your image view
imageView = (ImageView) findViewById(R.id.img);
//name of animation from anim directory
animSlide = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.left_to_right_anim);
// Start the animation like this
imageView.startAnimation(animSlide);
step 3:
now calculate time of animation and when your imageview animate at right side stop it and set it into your screen.
to achieve this you can user handler when you start your animation.
Thread's run() method is used to get time of your animation.
thanks ;)
What about using TransistionManager?
val slideRight= Slide()
slideRight.slideEdge = Gravity.RIGHT
slideRight.mode = Slide.MODE_IN
slideRight.addTarget(logoImageView)
slideRight.duration = ANIMATION_DURATION
TransitionManager.beginDelayedTransition(parentContainer, slideRight)
logoImageView.visibility = VISIBLE
It is snippet from my working code in Kotlin
Also you can use TransitionSet to combine animations

Set height of Snackbar in Android

I have a Snackbar in need to set its height or set height to wrap content. Is there any way?
Snackbar snack = Snackbar.make(findViewById(R.id.activity_container), "Message", Snackbar.LENGTH_SHORT);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
view.setBackgroundColor(Color.RED);
tv.setTextColor(Color.WHITE);
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
We are going to provide multiple answers. First a statement or two! You can set the height and width of a Snackbar but it is messy and time consuming period.
One realization about a Snackbar widget is most tutorials do not talk about styling. The opinion is they should be just the size that the widget gives you NOT MY VIEW. So we have noticed that the text size and number of max lines plays a BIG roll is the size of a well styled Snackbar. So design your Snackbar and style away
OK how to implement the mess Suggestion DO NOT DO THIS declare this variable where you would declare any other variable in your Activity
RelativeLayout rl;
Then when you need to increase the size of your RelativeLayout that is in your XML file but is not the root Layout in this case use this code
rl = (RelativeLayout) findViewById(R.id.svRL);
rl.getLayoutParams().height = 1480;
When you get done with this increased size which can mess with the size of other object in the root Layout you might want to set the size of the root Layout back to what it was. In this case the root Layout was set to layout height 615dp we are working with a Nexus 7 Tablet. If you have not noticed this yet here is the MESS part that 1480 is in units of pixels and you need it in dp. I am sure the conversion can be made just do not ask me. So here is the set back line of code
rl.getLayoutParams().height = 1230;
Now for a easy way to design and style two types of Snackbar's one with an Action button and one with out. First you need a CoordinatorLayout in what ever Activity corresponding XML file that looks like this Note it has an id
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coorSB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" >
<!-- android.support.design.widget.SnackBar -->
<!--stuff you want inside the coordinator ... -->
</android.support.design.widget.CoordinatorLayout>
Now we are ready to do some work in the Activity to design and style after a little advanced string and color set up. Please do not be offended I am being very thorough because you seem to be very new to programming.
<string name="snackbar_text">I Am a NEW SnackBAR TEXT</string>
<string name="snackbar_action">EXIT</string>
<string name="second_text">Second Text</string>
<string name="csb_text">I am the Custom Guy</string>
<string name="csb_action">EXIT</string>
<string name="the_text">Password must have one Numeric Value\n"
"One Upper & Lower Case Letters\n"
"One Special Character $ # ! % * ? &\n"
"NO Spaces in the PASSWORD"</string>
Now for the Rainbow many ways to manage Color this is my mine.
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303f9f</color>
<color name="colorAccent">#FF4081</color>
<color name="color_Black">#000000</color>
<color name="color_White">#FFFFFF</color>
<color name="color_darkGray">#606060</color>
<color name="color_lightGray">#C0C0C0</color>
<color name="color_super_lightGray">#E0E0E0</color>
<color name="color_Red">#FF0000</color>
<color name="color_Yellow">#FFFF66</color>
<color name="color_deepBlue">#0000ff</color>
<color name="color_lightBlue">#3333FF</color>
<color name="color_Purple">#9C27B0</color>
<color name="color_Transparent">#android:color/transparent</color>
Done with house keeping in your Activity where you declare variables add this
private CoordinatorLayout myLayout;
Snackbar sb = null;
private CoordinatorLayout noActLayout;
Snackbar sbNoAct = null;
There here is the implementation of both types of Snackbars
public void makeNoAct(View view){
// this is declared on a Button android:onClick="makeNoAct"
noActLayout = (CoordinatorLayout)findViewById(R.id.coorSB);
sbNoAct = Snackbar.make(noActLayout,R.string.the_text,1);// any interger will make it happy
sbNoAct.setDuration(3000);// 3 sec // OR Snackbar.LENGTH_LONG
// matters NOT you are setting duration
View sbView = sbNoAct.getView();
sbView.setBackgroundColor(ContextCompat.getColor(this, R.color.color_Black));
TextView textViewNoAct = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
//set text color
textViewNoAct.setTextColor(ContextCompat.getColor(this,R.color.color_Yellow));
textViewNoAct.setMaxLines(10);
textViewNoAct.setTextSize(24);
//increase max lines of text in snackbar. default is 2.
sbNoAct.show();
int height = sbView.getHeight();
etNewData.setText(String.valueOf(height));
}
public void makeCOOR(View view) {
// this is declared on a Button android:onClick="makeCOOR"
// We were to Lazy to write an OnClickListener
myLayout = (CoordinatorLayout) findViewById(R.id.coorSB);
sb = Snackbar.make(myLayout, R.string.csb_text, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.csb_action, myOnClickListener)
.setActionTextColor(ContextCompat.getColor(context, R.color.color_Red));
View sbView = sb.getView();
sbView.setBackgroundColor(ContextCompat.getColor(this, R.color.color_White));
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
//set text color
textView.setTextColor(ContextCompat.getColor(this,R.color.color_deepBlue));
textView.setTextSize(30);
//increase max lines of text in snackbar. default is 2.
textView.setMaxLines(10);
// NOTE new View
TextView textAction = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_action);
//set Action text color
textAction.setTextColor(ContextCompat.getColor(this,R.color.color_Red));
textAction.setTextSize(30);
sb.show();
}
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// OR use and Intent to go somewhere have a nice trip
sb.dismiss();
System.out.println("========= I WAS DISMISSED ===============");
}
};
Enjoy the code and let us know with a comment if this solves your issue.
This is very simple to change the height or width of Snackbar .
Just we need to write 2 , 3 line of code to do this.
Check the below code snippet .
Snackbar snackbar = Snackbar.make(view, "Your message", Snackbar.LENGTH_LONG);
snackbar.setAction("Ok", new View.OnClickListener() {
#Override
public void onClick(View view) {
//your click action.
}
});
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)snackbar.getView();
layout.setMinimumHeight(50);//your custom height.
snackbar.show();
final String CR= System.getProperty("line.separator") ;
String snackMsg= "First line" + CR;
snackMsg+="Second line." +CR;
snackMsg+="... more lines." +CR;
final Snackbar snack = Snackbar.make(findViewById(android.R.id.content), snackMsg, Snackbar.LENGTH_INDEFINITE);
snack.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
// Respond to the click, such as by undoing the modification that caused
// this message to be displayed
}
});
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
// tv.setBackgroundColor(Color.RED);
tv.setLines(12);
FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
//params.height=2000;
params.bottomMargin=10;
view.setLayoutParams(params);
snack.show();
You may also need to set the size for the inner container of a snackbar in order for the text to be aligned/centered vertically. Here is a solution (Kotlin):
Snackbar.make( containerView, msg, duration ).also {
// outer container
it.view.minimumHeight = minHeightPx
// inner container
( it.view as? Snackbar.SnackbarLayout )?.getChildAt( 0 )?.let { innerView ->
innerView.minimumHeight = minHeightPx
}
}.show()
Snackbar snack = Snackbar.make(findViewById(R.id.activity_container), "Message", Snackbar.LENGTH_SHORT);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.height = 80;
tv.setTextColor(Color.WHITE);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setLayoutParams(params);
snack.show();

Display images through array in Android Studio

I'm trying to re-rig a quiz app to instead of displaying text questions, will display images (Ishihara slides to be specific).
For reference, here's a screenshot of the original quiz app:
When a user selects the true or false buttons, a toast appears with the result. Straightforward, and the previous/next buttons cycle through the questions. The questions are being stored as such:
final QuestionAndAnswer[] mQandA = new QuestionAndAnswer[]{
/*1*/ new QuestionAndAnswer(R.string.question_northAmerica, true),
/*2*/ new QuestionAndAnswer(R.string.question_antarctica, false),
/*3*/ new QuestionAndAnswer(R.string.question_canada, false),
/*4*/ new QuestionAndAnswer(R.string.question_madagascar, true),
/*5*/ new QuestionAndAnswer(R.string.question_wonders, false)
};
I thought that pointing the new QuestionAndAnswer at R.drawable.imagename could accomplish this, but instead just displays the image's location as text.
And changing it to new ImageView(R.drawable.imagename, true) throws the error:
ImageView (android.content.Context, android.util.AttributeSet)in ImageView cannot be applied to (int,boolean)
I'm sorry, I'm still very new to Android but as you've probably put together by now, I'm a student and don't have a choice but to do this.
If you have something like this on layout xml
<RelativeLayout ...
...
<TextView android:id="#+id/text_view_id" ... />
...
</RelativeLayout>
You need to change it to
<RelativeLayout ...
...
<ImageView android:id="#+id/image_view_id" ... />
...
</RelativeLayout>
Then on your activity class, maybe you have something like below
TextView textView;
public void onCreate() {
textView = (TextView) findViewById(R.id.text_view_id);
....
textView.setText(mQandA[i].question)
}
Where mQandA[i].question is your question resource a.k.a R.string.question_northAmerica
Change it to
ImageView imageView;
public void onCreate() {
imageView = (ImageView) findViewById(R.id.image_view_id);
...
imageView.setImageResource(mQandA[i].question)
}
Where mQandA[i].question is your image resource a.k.a R.drawable.imagename
EDIT 1
change every appearance of
textView.setText(mQandA[i].question)
with
imageView.setImageResource(mQandA[i].question)
counterpart

I need help on android Toast view as icon on error

My activity is a Video Player Activity and its working fine, On some Videos it must throw a message (handleHardwareAccelerationError) if the video is not supported or high quality.
It shows as Toast with message fine.
Now I would like to change this Toast message to show a picture or small icon instead, is this possible? Here is my code for handleHardwareAccelerationError, Thanks in advance.
private void handleHardwareAccelerationError() {
mHardwareAccelerationError = true;
if (mSwitchingView)
return;
Toast.makeText(this, R.string.hardware_acceleration_error, Toast.LENGTH_LONG).show();
}
what I have tried is this but didnt show anything.
private void handleHardwareAccelerationError() {
mHardwareAccelerationError = true;
if (mSwitchingView)
return;
final View popupView = getLayoutInflater().inflate(R.layout.myinforbar, null);
mError = (ImageView) popupView.findViewById(R.id.errornew);
mError.setVisibility(View.VISIBLE);
}
and here is myinforbar.xml
<LinearLayout android:gravity="center_vertical" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="21dp" android:layout_marginLeft="0.0dip" android:layout_marginTop="5.0dip"
android:background="#drawable/button5_background">
<ImageView
android:id="#+id/errornew"
android:src="#drawable/everyone_icon_nearby_cur"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:visibility="invisible"/>
</LinearLayout>
EDITED:
The original activity is long and it can be found here rather then pasting the whole activity you can see it here VideoPlayerActivity
( private void handleHardwareAccelerationError)
New Update...
This is without the message (onHardwareError) applied, I want to see icon inside this bottom little box that popup when video playing (infobar) instead of Toast message.
Toast is farily limited, you cannot show icons.
Edit: Gunjav Dave says it's possible, so it's approach worth a try.
Anyway this free library: SuperToast
can make what you need.
If you prefer to stick to Google's standards you can use, instead, the Snackbars, that don't allow, as far as I know, to put an icon, but can anyway be associated with an action/button, and they are standard.
I can't understand what you try to do with popupView, if you want to use a PopupWindow you have to use a completely different syntax. This Balloon Popup library of mine helps you to make a popup attached to a View, using a PopupWindow, you can also inflate into it a layout, or use it as an example on how to make a PopupWindow.
Edit:
You are inflating a layout inside a view, but this doesn't show the view. Instead, you should use a PopupWindow, and inflate inside it a layout.
This is an example taken from my BalloonPopup library:
// ....
hostedView = ((LayoutInflater) ctx.getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(layoutRes, null);
textView = (TextView) hostedView.findViewById(R.id.text_view);
textView.setText(text);
// ....
popupWindow = new PopupWindow(hostedView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
In other words, you should be able to do something like
PopupWindow popupWindow = new popupWindow(mError, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
in your code to show the popup window.
These are the essential points of the code, then you can reposition the popup, and eventually keep track of it to edit and re-show it instead of always creating from scratch. Please consider, anyway, to use BalloonPopup library, that does what you need, without getting crazy with animations, display times, window's permanence and positioning. You can just inflate into it your layout, for example with an icon and a text, and make it appear exactly on the center of another View, that can be your (already present) media player.
More edit:
Another very simple solution.
To get it simple, create a RelativeLayout, that hosts all your video player, and then create a simple ImageView in the center of it. Set its visibility to GONE when hidden and to VISIBLE when the error must be shown. Subsequently, you can use a timer or a touchListener to close it making it GONE again.
Try this
private void handleHardwareAccelerationError() {
mHardwareAccelerationError = true;
if (mSwitchingView)
return;
final View popupView = getLayoutInflater().inflate(R.layout.myinforbar, null);
PopupWindow pw = new PopupWindow(popupView , 300, 400, true);
pw.showAtLocation(popupView , Gravity.CENTER, 0, 0);
mError = (ImageView) popupView.findViewById(R.id.errornew);
mError.setVisibility(View.VISIBLE);
}
XML Name or Layout Name would be
<LinearLayout xmlns:androidclass="http://schemas.android.com/apk/res/android"
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button5_background">
<ImageView
android:id="#+id/errornew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"/>
</LinearLayout>
Put This in Class:
LayoutInflater inflater = LayoutInflater.from(this);
View layout= inflater.inflate(R.layout.myinforbar, null);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);
toast.show();

Preferences to change the background animation of an app

I am trying to make Settings in the app, specificly a ListPreference to be able to change the background animation of the app, but I can't do it, nothing changes if you choose option 1 or option 2... I followed a similar tutorial and tried to make it work for me, but nothing so far.
Here is the java
SharedPreferences backChooser = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String values = backChooser.getString("list", "1");
img = (ImageView) findViewById(R.id.imageView1);
img.setBackgroundResource(R.drawable.anim1);
animation = (AnimationDrawable) img.getDrawable();
animation.start();
if (values.contentEquals("1")) {
img.setBackgroundResource(R.drawable.anim1);
animation = (AnimationDrawable) img.getDrawable();
animation.start();
}
if (values.contentEquals("2")) {
img.setBackgroundResource(R.drawable.anim2);
animation = (AnimationDrawable) img.getDrawable();
animation.start();
}
and here is the xml of the preferences
<?xml version="1.0" encoding="utf-8"?>
<ListPreference
android:entries="#array/list"
android:entryValues="#array/listvalues"
android:key="list"
android:summary="This is a list to choose from"
android:title="List" />
This line of code
img.setBackgroundResource(R.drawable.anim1);
sets an ImageView's "Background".
Were as this code
img.getDrawable();
gets an ImageView's "Drawable" or the image on it, not the actual "Background" image.
Since you want to retrieve the image that you've once set as the BG of "img", this code
img.getBackground();
is the one that you need.

Categories

Resources