RelativeLayout align parent bottom does not align at bottom - android

I have a custom circular layout using a relative layout:
public class CircularLayout extends RelativeLayout implements OnDragListener {
private DropCallback onDrop = null;
private ImageButton imageButton = null;
private ImageView imageViewBackgroundWave = null;
private int radius = -1;
private double step = -1;
private double angle = -1;
private static final int CENTER_ID = 111;
public CircularLayout(Context context, DropCallback onDrop, int radius, List<View> views) {
super(context);
this.onDrop = onDrop;
this.radius = radius;
this.step = (2 * Math.PI) / views.size();
this.initView(context, views);
}
private void initView(Context context, List<View> views) {
RelativeLayout.LayoutParams layoutParamsView = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
this.setLayoutParams(layoutParamsView);
RelativeLayout.LayoutParams layoutParamsImageview = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParamsImageview.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParamsImageview.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
this.imageViewBackgroundWave = new ImageView(this.getContext());
this.imageViewBackgroundWave.setLayoutParams(layoutParamsImageview);
this.imageViewBackgroundWave.setImageDrawable(this.getResources().getDrawable(R.drawable.background_wave));
this.addView(this.imageViewBackgroundWave);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
this.imageButton = new ImageButton(context);
this.imageButton.setId(CENTER_ID);
this.imageButton.setLayoutParams(layoutParams);
this.imageButton.setImageResource(R.drawable.ic_power_on);
this.imageButton.getBackground().setAlpha(0);
this.imageButton.setOnDragListener(this);
this.addView(this.imageButton);
for(View view : views) {
this.addView(this.placeView(view));
}
}
private View placeView(View view) {
view.measure(0, 0);
this.imageButton.measure(0, 0);
int x = (int)((view.getMeasuredWidth() / 2) + this.radius * Math.cos(this.angle));
int y = (int)((view.getMeasuredHeight() / 2) + this.radius * Math.sin(this.angle));
this.angle += this.step;
int deltaX = view.getMeasuredWidth();
int deltaY = view.getMeasuredHeight();
int deltaImageX = this.imageButton.getMeasuredWidth() / 2;
int deltaImageY = this.imageButton.getMeasuredHeight() / 2;
int xToDraw = ((x - deltaX) - deltaImageX);
int yToDraw = ((y - deltaY) - deltaImageY);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ABOVE, CENTER_ID);
layoutParams.addRule(RelativeLayout.RIGHT_OF, CENTER_ID);
layoutParams.setMargins(xToDraw, 0, 0, yToDraw);
view.setLayoutParams(layoutParams);
return view;
}
#Override
public boolean onDrag(View view, DragEvent event) {
return this.onDrop.onDrop(view, event);
}
}
Unfortunately the imageview (imageViewBackgroundWave) is not aligning at the bottom. It aligns a little bit higher:
So the question is: how can I align my imageview to the bottom of the screen?
The image is exactly as high and as wide as the blue stripe. there is no
padding or white color in it. Its just the blue stripe shown in the picture above.
EDIT:
The background_wave.png:
I use this custom layout in my MenuFragment and call it with the following code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ... init the imagebuttons in the list of views
this.circleView = new CircularLayout(this.getActivity(), this, 250, views);
this.circleView.setOnDragListener(this);
this.circleView.setBackground(this.getResources().getDrawable(R.drawable.background));
return this.circleView;
}

You can get the ImageView to stick to the bottom by adding this line of code:
imageView.setScaleType(ScaleType.FIT_END);
The reason for the weirdness is that the ImageView bounds are calculated by the layout engine first, then the image inside the ImageView is scaled to fit the allocated area according to the scale type.
Using WRAP_CONTENT for the ImageView allocates an area based on the size of the unscaled image bitmap - even if it is larger than the screen. Your background_wave.png file is wider than the screen, so a larger area than is needed is allocated. Then afterwards when the image gets fitted inside the layout area using FIT_CENTER it gets shrunk down and centered, so you end up up with white space above and below it.
You can verify this by resizing your background_wave.png to be 1/4 the size: it should align the bottom even without the above code change.

You are setting width and height twice with RelativeLayout.LayoutParams.WRAP_CONTENT and RelativeLayout.ALIGN_PARENT_BOTTOM
Try this:
private void initView(Context context) {
RelativeLayout.LayoutParams layoutParamsView = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
this.setLayoutParams(layoutParamsView);
RelativeLayout.LayoutParams layoutParamsImageview = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
this.imageView = new ImageView(this.getContext());
this.imageView.setLayoutParams(layoutParamsImageview);
this.imageView.setImageDrawable(this.getResources().getDrawable(R.drawable.background_wave));
this.addView(this.imageView);
}
I also recommend you to use visual designer with XML to test layout's rules and parameters, then, if you need it, you can set that rules in code to get the same result.

Related

i m using 4 imageview in relativelayout and i want to make dynamically. u can see screenshot below

i m using 4 imageview in relativelayout and that images size equal to each other in relative layout but want to make dynamically but i m not getting
Heading
final ImageView profile_img1 = (ImageView) view.findViewById(R.id.profile_img1);
final ImageView profile_img2 = view.findViewById(R.id.profile_img2);
Display display = activity.getWindowManager().getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
final double margin_15 = width * 0.15;
final RelativeLayout relativeLayout=view.findViewById(R.id.relative_profile);
RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
parms.setMargins((int) margin_15, 0, (int) margin_15, 0);
relativeLayout.setLayoutParams(parms);
// Toast.makeText(activity,width+"",Toast.LENGTH_SHORT).show();
relativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
relativeLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
width_relativelayout = relativeLayout.getMeasuredWidth();
h_relativelayout = relativeLayout.getMeasuredHeight();
// Toast.makeText(activity,width_linearlayout+"===",Toast.LENGTH_SHORT).show();
RelativeLayout.LayoutParams parms_img = new RelativeLayout.LayoutParams( width_relativelayout/2,350);
parms_img.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
profile_img1.setLayoutParams(parms_img);
RelativeLayout.LayoutParams parms_img2 = new RelativeLayout.LayoutParams(width_relativelayout/2,300);
parms_img.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
profile_img1.setLayoutParams(parms_img2);
profile_img2.setLayoutParams(parms_img2);
}
});
You can use RecyclerView and Adapter for same.
and Set GridLayoutManager with number count to show, like 2 for two image view horizontally.
Or you can ArrayList of ImageView.

Custom View in Relative Layout overlapping other Custom Views [duplicate]

Is it possible to set the absolute position of a view in Android? (I know that there is an AbsoluteLayout, but it's deprecated...)
For example, if I have a 240x320px screen, how could I add an ImageView which is 20x20px such that its center is at the position (100,100)?
You can use RelativeLayout. Let's say you wanted a 30x40 ImageView at position (50,60) inside your layout. Somewhere in your activity:
// Some existing RelativeLayout from your layout xml
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv = new ImageView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
More examples:
Places two 30x40 ImageViews (one yellow, one red) at (50,60) and (80,90), respectively:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
iv = new ImageView(this);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;
rl.addView(iv, params);
Places one 30x40 yellow ImageView at (50,60) and another 30x40 red ImageView <80,90> relative to the yellow ImageView:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
int yellow_iv_id = 123; // Some arbitrary ID value.
iv = new ImageView(this);
iv.setId(yellow_iv_id);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;
// This line defines how params.leftMargin and params.topMargin are interpreted.
// In this case, "<80,90>" means <80,90> to the right of the yellow ImageView.
params.addRule(RelativeLayout.RIGHT_OF, yellow_iv_id);
rl.addView(iv, params);
In general, you can add a View in a specific position using a FrameLayout as container by specifying the leftMargin and topMargin attributes.
The following example will place a 20x20px ImageView at position (100,200) using a FrameLayout as fullscreen container:
XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root"
android:background="#33AAFF"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
Activity / Fragment / Custom view
//...
FrameLayout root = (FrameLayout)findViewById(R.id.root);
ImageView img = new ImageView(this);
img.setBackgroundColor(Color.RED);
//..load something inside the ImageView, we just set the background color
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(20, 20);
params.leftMargin = 100;
params.topMargin = 200;
root.addView(img, params);
//...
This will do the trick because margins can be used as absolute (X,Y) coordinates without a RelativeLayout:
Just to add to Andy Zhang's answer above, if you want to, you can give param to rl.addView, then make changes to it later, so:
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
Could equally well be written as:
params = new RelativeLayout.LayoutParams(30, 40);
rl.addView(iv, params);
params.leftMargin = 50;
params.topMargin = 60;
So if you retain the params variable, you can change the layout of iv at any time after adding it to rl.
A more cleaner and dynamic way without hardcoding any pixel values in the code.
I wanted to position a dialog (which I inflate on the fly) exactly below a clicked button.
and solved it this way :
// get the yoffset of the position where your View has to be placed
final int yoffset = < calculate the position of the view >
// position using top margin
if(myView.getLayoutParams() instanceof MarginLayoutParams) {
((MarginLayoutParams) myView.getLayoutParams()).topMargin = yOffset;
}
However you have to make sure the parent layout of myView is an instance of RelativeLayout.
more complete code :
// identify the button
final Button clickedButton = <... code to find the button here ...>
// inflate the dialog - the following style preserves xml layout params
final View floatingDialog =
this.getLayoutInflater().inflate(R.layout.floating_dialog,
this.floatingDialogContainer, false);
this.floatingDialogContainer.addView(floatingDialog);
// get the buttons position
final int[] buttonPos = new int[2];
clickedButton.getLocationOnScreen(buttonPos);
final int yOffset = buttonPos[1] + clickedButton.getHeight();
// position using top margin
if(floatingDialog.getLayoutParams() instanceof MarginLayoutParams) {
((MarginLayoutParams) floatingDialog.getLayoutParams()).topMargin = yOffset;
}
This way you can still expect the target view to adjust to any layout parameters set using layout XML files, instead of hardcoding those pixels/dps in your Java code.
Just in case it may help somebody, you may also try this animator ViewPropertyAnimator as below
myView.animate().x(50f).y(100f);
myView.animate().translateX(pixelInScreen)
Note: This pixel is not relative to the view. This pixel is the pixel
position in the screen.
credits to bpr10 answer
Place any view on your desire X & Y point
layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.MainActivity" >
<AbsoluteLayout
android:id="#+id/absolute"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="#+id/rlParent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/btn_blue_matte" />
</RelativeLayout>
</AbsoluteLayout>
</RelativeLayout>
Java Class
public class MainActivity extends Activity {
private RelativeLayout rlParent;
private int width = 100, height = 150, x = 20, y= 50;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AbsoluteLayout.LayoutParams param = new AbsoluteLayout.LayoutParams(width, height, x, y);
rlParent = (RelativeLayout)findViewById(R.id.rlParent);
rlParent.setLayoutParams(param);
}
}
Done
Try below code to set view on specific location :-
TextView textView = new TextView(getActivity());
textView.setId(R.id.overflowCount);
textView.setText(count + "");
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
textView.setTextColor(getActivity().getResources().getColor(R.color.white));
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// to handle click
}
});
// set background
textView.setBackgroundResource(R.drawable.overflow_menu_badge_bg);
// set apear
textView.animate()
.scaleXBy(.15f)
.scaleYBy(.15f)
.setDuration(700)
.alpha(1)
.setInterpolator(new BounceInterpolator()).start();
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.topMargin = 100; // margin in pixels, not dps
layoutParams.leftMargin = 100; // margin in pixels, not dps
textView.setLayoutParams(layoutParams);
// add into my parent view
mainFrameLaout.addView(textView);
My code for Xamarin,
I am using FrameLayout for this purpose and following is my code:
List<object> content = new List<object>();
object aWebView = new {ContentType="web",Width="300", Height = "300",X="10",Y="30",ContentUrl="http://www.google.com" };
content.Add(aWebView);
object aWebView2 = new { ContentType = "image", Width = "300", Height = "300", X = "20", Y = "40", ContentUrl = "https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4" };
content.Add(aWebView2);
FrameLayout myLayout = (FrameLayout)FindViewById(Resource.Id.frameLayout1);
foreach (object item in content)
{
string contentType = item.GetType().GetProperty("ContentType").GetValue(item, null).ToString();
FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(Convert.ToInt32(item.GetType().GetProperty("Width").GetValue(item, null).ToString()), Convert.ToInt32(item.GetType().GetProperty("Height").GetValue(item, null).ToString()));
param.LeftMargin = Convert.ToInt32(item.GetType().GetProperty("X").GetValue(item, null).ToString());
param.TopMargin = Convert.ToInt32(item.GetType().GetProperty("Y").GetValue(item, null).ToString());
switch (contentType) {
case "web":{
WebView webview = new WebView(this);
//webview.hei;
myLayout.AddView(webview, param);
webview.SetWebViewClient(new WebViewClient());
webview.LoadUrl(item.GetType().GetProperty("ContentUrl").GetValue(item, null).ToString());
break;
}
case "image":
{
ImageView imageview = new ImageView(this);
//webview.hei;
myLayout.AddView(imageview, param);
var imageBitmap = GetImageBitmapFromUrl("https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4");
imageview.SetImageBitmap(imageBitmap);
break;
}
}
}
It was useful for me because I needed the property of view to overlap each other on basis of their appearance, e.g the views get stacked one above other.

Android ViewGroup: what should I do in the onLayout() override?

When extending an Android ViewGroup class, what is the purpose of the onLayout() override? I'm making a custom control in Android but for some reason the content (child View objects) isn't displaying. My approach was to extend the ViewGroup class, adding child-Views via the addView() method of ViewGroup. Then, in my main activity, I have the following code:
ChannelController myCC = new ChannelController(this);
setContentView(myCC);
ChannelController is the name of my custom class that extends ViewGroup. I must be doing something wrong because nothing is shown on the screen.
I understand that I must override and implement the onLayout() method, but with what? I know there's an entire page dedicated to this on the dev.android site, but it didn't help me much, mostly because I'm a newbie I guess. Any insight would be appreciated.
For reference, my ViewGroup extension looks like below:
public class ChannelController extends ViewGroup {
final String TAG = "JAL";
public ChannelController(Context c)
{
super(c);
init(c);
}
public ChannelController(Context c, AttributeSet attibset)
{
super(c);
init(c);
}
public ChannelController(Context c, AttributeSet attribset, int defStyle)
{
super(c);
init(c);
}
public void init(Context c)
{
//RelativeLayout wrap = new RelativeLayout(c);
RelativeLayout.LayoutParams wrapLP = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout r1 = new RelativeLayout(c);
RelativeLayout.LayoutParams r1LP = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout r2 = new RelativeLayout(c);
RelativeLayout.LayoutParams r2LP = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
TextView t = new TextView(c);
RelativeLayout.LayoutParams tlp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button m = new Button(c);
RelativeLayout.LayoutParams mlp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button s = new Button(c);
RelativeLayout.LayoutParams slp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
SeekBar f = new SeekBar(c);
RelativeLayout.LayoutParams flp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
t.setId(1);
m.setId(2);
s.setId(3);
f.setId(4);
r1.setId(5);
r2.setId(6);
t.setText("CHANNELNAME");
t.setTextColor(Color.BLACK);
tlp.setMargins(30, 0, 0, 0);
tlp.addRule(RelativeLayout.LEFT_OF, m.getId());
tlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
tlp.addRule(RelativeLayout.CENTER_VERTICAL);
tlp.addRule(RelativeLayout.CENTER_HORIZONTAL);
m.setText("M");
m.setBackgroundColor(Color.rgb(237, 155, 31));
m.setTextColor(Color.WHITE);
mlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
mlp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
m.setTextSize(10);
flp.addRule(RelativeLayout.LEFT_OF, s.getId());
flp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
flp.addRule(RelativeLayout.CENTER_VERTICAL);
s.setText("S");
s.setTextSize(10);
s.setBackgroundColor(Color.rgb(192, 48, 46));
s.setTextColor(Color.WHITE);
slp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
slp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
r1.addView(t, tlp);
r1.addView(m, mlp);
r2.addView(f, flp);
r2.addView(s, slp);
r1.setBackgroundColor(Color.rgb(233, 242, 251));
r2.setBackgroundColor(Color.rgb(233, 242, 251));
r1LP.addRule(RelativeLayout.ALIGN_PARENT_TOP);
r2LP.addRule(RelativeLayout.BELOW, r1.getId());
this.addView(r1, r1LP);
this.addView(r2, r2LP);
this.setLayoutParams(wrapLP);
//this.addView(wrap);
Log.i(TAG, "ChannelController constructor was called");
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
//super.onLayout(changed, l, t, r, b);
}
}
What do I need to do in the onLayout method override?
In onLayout you need to call layout method on each child of this ViewGroup and provide desired position (relatively to parent) for them. You can check source code of FrameLayout (one of the simpliest subclasses of ViewGroup) to find out how it works.
Although, if you don't need any "special" layouting, you have other options:
Extend some another subclass of ViewGroup instead (FrameLayout for example)
Use LayoutInflater if you just need your control to look exactly as in XML (which, I think, is exactly your case)
Actually it helps in positioning children of a view group. following code may help
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
MarginLayoutParams layoutParams = (MarginLayoutParams) icon.getLayoutParams();
// Figure out the x-coordinate and y-coordinate of the icon.
int x = getPaddingLeft() + layoutParams.leftMargin;
int y = getPaddingTop() + layoutParams.topMargin;
// Layout the icon.
icon.layout(x, y, x + icon.getMeasuredWidth(), y + icon.getMeasuredHeight());
// Calculate the x-coordinate of the title: icon's right coordinate +
// the icon's right margin.
x += icon.getMeasuredWidth() + layoutParams.rightMargin;
// Add in the title's left margin.
layoutParams = (MarginLayoutParams) titleView.getLayoutParams();
x += layoutParams.leftMargin;
// Calculate the y-coordinate of the title: this ViewGroup's top padding +
// the title's top margin
y = getPaddingTop() + layoutParams.topMargin;
// Layout the title.
titleView.layout(x, y, x + titleView.getMeasuredWidth(), y + titleView.getMeasuredHeight());
// The subtitle has the same x-coordinate as the title. So no more calculating there.
// Calculate the y-coordinate of the subtitle: the title's bottom coordinate +
// the title's bottom margin.
...
you can find more detail about custom views here
custom views

Design dynamic hotspot on Image in Android

I have to develop a UI like below:
I want to show this type of image and show hotspot on that image. The position of hotspot will be dynamic, as per x,y and radius provided the circle will be drawn on the original picture. The user can click on the hotspots and onclick action will be defined on the specific hotspot on which the user will click.
What is best process to develop this type of UI?
Make your main layout a RelativeLayout and then you can add programmatically a ImageView with an onClickListener to your layout with the following code:
private void addImageView(RelativeLayout mainLayout, int x, int y, int width, int height, OnClickListener onClickListener){
ImageView imageView = new ImageView(this);
imageView.setAdjustViewBounds(false);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.height = height;
params.width = width;
imageView.setLayoutParams(params);
imageView.setScaleType(ImageView.ScaleType.FIT_XY); //remove this if you want to keep aspect ratio
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher)); //here goes your drawable
params.leftMargin = x - width/2;
params.topMargin = y - height/2;
imageView.setOnClickListener(onClickListener);
mainLayout.addView(imageView);
}
to use it you call:
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout); //this is your main layout
addImageButton(mainLayout, 200, 300, 200, 200, new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
}
});
You can also use a ImageButton to achive the same porpose, although the image size will be affected by button border:
private void addImageButton(RelativeLayout mainLayout, int x, int y, int width, int height, OnClickListener onClickListener){
ImageButton imageButton = new ImageButton(this);
imageButton.setAdjustViewBounds(true);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.height = height;
params.width = width;
imageButton.setLayoutParams(params);
imageButton.setScaleType(ImageView.ScaleType.FIT_XY);
imageButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
params.leftMargin = x - width/2;
params.topMargin = y - height/2;
imageButton.setOnClickListener(onClickListener);
mainLayout.addView(imageButton);
}
Try it.

Setting margins on RelativeLayout doesnt work on Kindle Fire

This is similar to my previous question but it didnt work with the Kindle Fire (2.3.4).
I used a FragmentTransaction to add a Fragment into a FrameLayout. I want to dynamically change the margin of the RelativeLayout used by the Fragment.
However, the margins are not changing with FrameLayout.layoutParams on the Kindle Fire. However, this works on 3.2.1. I also tried using setMargins() and it didnt work.
Does anyone know how I can dynamically change the margins on the Kindle Fire?
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.infocard, container, false);
RelativeLayout infoLayout = (RelativeLayout) view.findViewById(R.id.info);
infoLayout.setOnClickListener(new EmptyClickListener());
final int width = 250;
final int height = 270;
int leftMargin = 0;
int topMargin = 0;
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height);
if (x - width < 0) {
leftMargin = 0;
} else {
leftMargin = x - width + 40;
}
if (y >= 400 && y <= 480) {
topMargin = 160;
}
params.leftMargin = leftMargin;
params.topMargin = topMargin;
//params.setMargins(leftMargin, topMargin, 0, 0); //this didnt work either
infoLayout.setLayoutParams(params);
TextView titleView = (TextView) view.findViewById(R.id.titleCard);
titleView.setText(title);
return view;
}
Ok I was able to fix this by wrapping my infoLayout in another RelativeLayout, and now it works perfectly

Categories

Resources