Home » Java » java – Android – Program ImageView Constraints in Custom Toast Class-Exceptionshub

java – Android – Program ImageView Constraints in Custom Toast Class-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have successfully add an ImageView to a CUSTOM TOAST VIEW GROUP.

Right now that ImageView is horizontally centered in the bottom of the screen.

What I wish to do is to constraint this widget to the top of the screen and later put it some top margins. However I can’t find the methods name that allows this to happen? Does it even exist? Is there a different solution to this scenario?

How do I programmatically constraint this ImageView to the top of the toast view?

public class CustomToast extends android.widget.Toast{

public CustomToast(String toast_text, Context toast_context, int toast_status) {
    super(toast_context);

    // TOAST
    Toast toast = Toast.makeText(toast_context, toast_text, Toast.LENGTH_LONG);

    // VIEW
    ViewGroup view = (ViewGroup) toast.getView();

    // BACKGROUND
    view.setBackgroundResource(R.drawable.background_toast);

    // IMAGE VIEW
    ImageView myImage = new ImageView(toast_context);
    myImage.setImageResource(R.drawable.icon_toast_valid);
    myImage.setMaxWidth(200);
    myImage.setMaxHeight(200);
    myImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    myImage.setAdjustViewBounds(true);

    view.addView(myImage);

    // SHOW
    toast.show();
}

}

I have checked the android documentation, some stackoverflow links and even tried to find the method through the Android Studio intelligent code completion. So far I haven’t been capable of solving this problem…

How to&Answers:

In Android you have View and ViewGroups.
The ViewGroups can contain childs, and this childs can be other View or ViewGroups.

The View have behave to himself (color, size, orientation…).
The ViewGroups have order behave to himself and his childs.

The most used ViewGroups are:

  • FrameLayout
  • LinearLayout
  • RelativeLayout
  • ConstraintLayout

Depending on your what you need you got to choose.

  • FrameLayout order his child like a Stack of Views in the same way you
    are declaring in the xml.
  • LinearLayout arranges other views either horizontally in a single
    column or vertically in a single row.
  • RelativeLayout has references between childs to order.
  • ConstraintLayout has “constraints” to order his childs, it is like
    RelativeLayout but most powerful.

In your implementation you have a “programmatically” implementation, maybe if you try to use the xml will be more simple.