How to add a view to another in android? - android

Is there any way to add a view to another at specified place? i.e I want to add a child view at (x, y) location of parent view. Please help me.
parentView.addView(childView);

You can do this by using the LayoutParams in a RelativeLayaout
An example:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params.leftMargin = 50; //Your X coordinate
params.topMargin = 60; //Your Y coordinate
parentView.addView(childView,params);

You can't add a view at (x,y) location of the parent. However you can trick it to achieve something like this:
Have your parent be RelativeLayout
Define your child view with android:layout_alignParentLeft="true", android:layout_alignParentTop="true", android:layout_marginLeft="X" android:layout_marginTop="Y" (or define the same things via code using LayoutParams)
Add your child to your parent: parentView.addView(childView)

Related

android , moving view in linearlayout

I made a linear layout and it contain some Image views . when i move one with (set X(view.get x + 10)) function, it moves... but it moves behind other views. that the view become hidden.
and the other problem is when i get X & Y of the view, its always 0,0. but the view is in the middle of the screen. what should I do??? should i give up with linear layout??
if(wichmov == "right" ){
if(martin.getX() < width){
martin.setX(martin.getX()+ deltax);
}
else if(wichmov == "left"){
if(martin.getX() > 0){
martin.setX(martin.getX()- deltax );
}
}
}
this is how i move it.
When are you trying to call getX()? This might be something to look into: View getX() and getY() return 0.0 after they have been added to the Activity
If you're making the call in onCreate, it'll be zero.
I just figured it out.
I use a relative layout and then set the linear layout as match parent. After designing the background with the linear layout, I define an image view after the linear layout and inside of the relative layout, and then in Java, I set the position of it in the exact place I want it to (front of the special box of linear layout that I wanted it move), and width and height of it too.
The following code will help you to place your view to the exact place of your screen you want it, and set its width and height:
DisplayMetrics metrics = this.getResources().getDisplayMetrics(); //getting screen size
width = metrics.widthPixels;
height = metrics.heightPixels;
view.setX(width *5/8); //setting the place
view.setY(height/4);
LayoutParams para = view.getLayoutParams(); //set size of view
para.height = (int) (height/2);
para.width = (int) (width/4);
view.setLayoutParams(para);

get position of view with respect to top-most parent in android

To get a view relative to its parent, I can use getLeft(), getRight(), getTop(), and getBottom(). But how do I get a view relative to the top-most parent of the layout file?
So say my eve layout is RelativeLayout. Then say inside eve I have a number of nested layouts. And then deep within the hierarchy I have a EditText view. How do I get the location of the EditText view with respect to eve?
To find out absolute view location, you can use view.getLocationOnScreen() or view.getLocationInWindow().
View target = findViewById(R.id.target_id);
View parent = (View)target.getParent();
int x = target.getLeft();
int y = target.getTop();
while(parent != null){
x += parent.getLeft();
y += parent.getTop();
parent = (View)parent.getParent()
}
These code may be help you, because I didn't test it. I hope it would work.

How to get coordinate of view in LinearLayout

I have a LinearLayout which can have many child views. Child views are added programatically.
i need this distance
<---------------------->
--------------------------------wrapper ln----------------------------------
- ... cv4 cv3 cv2 cv1 -
----------------------------------------------------------------------------
Wrapper ln gravity is setted to right, so every added child view putting right.
For example when I click to "cv4" i need to get the distance from the right side of wrapper linear layout.
Child views are of LinearLayout type.
You can call getWidth() on the parent LinearLayout and getLeft() on the dynamically added view to get the position from the right:
parent.getWidth() - c4.getLeft();
You can also hook onto a OnGlobalLayoutListener so you can get the co-ordinates every time it changes its dimensions:
parent.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
int right = parent.getWidth() - c4.getLeft();
}
}

When is the width of an Android View set?

I have a little issue on what sequence things are being called when adding stuff to a RelativeLayout. I have a class extending Activity (name it RelActivity) where I want to create a RelativeLayout and put several custom Views (name it cusView) into that RelativeLayout. The topMargin and leftMargin of a custom View is calculated by using the position of another custom View (i.e. the first custom View has to be positioned directly by setting a number to topMargin and leftMargin). Please note that the Rules of RelativeLayout is not sufficient in this case.
So, over to the problem. In my RelActivity I do this:
Create a RelativeLayout (name it relLayout)
Iterate a cursor with cusViews recieved from a database
For the first cusView -> Set position by topMargin and leftMargin using a LayoutParameter
For the other cusViews -> calculate their topMargin and leftMargin by using one of the other cusViews and a LayoutParameter
Set RelActivity's contentView to relLayout
What happens is that all cusViews but the first one are squeezed in the top left corner because both leftMargin and topMargin are always calculated to be zero. This happens because I use the width of the cusViews to calculate the topMargin and leftMargin, and the width of the cusView has not given a value yet.
Is the width first calculated in the cusView's overrided method onSizeChanged()? Is the onSizeChanged() method get called first when the layout is presented on the screen? If so, how do I work around this issue? Do I have to calculate the positionings after onSizeChanged() is done?
Edit: Here is a minimum working example:
Here is my onCreate in RelActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
relLayout = new RelativeLayout(this);
cusViews = new ArrayList<CusView>();
listParams = new ArrayList<RelativeLayout.LayoutParams>();
readDBandSetLayout();
setContentView(relLayout);
}
There is too much information in the readDBandSetLayout() method to present it all here. below are the most important details. If I create the LayoutParams in the following way it works fine, the cusViews are listed downwards and rightwards of eachother:
queryCursor = customApplication.customData.query( number); //Fetches cursor
for ( int i = 0; i < numberOfRows; i++ ){
if ( i == 0 ){
LayoutParams p = new LayoutParams(this.getResources().getDimensionPixelSize(R.dimen.small), this.getResources().getDimensionPixelSize(R.dimen.small));
p.topMargin = 50;
p.leftMargin = 50;
listParams.add(p);
}
else{
LayoutParams p = new LayoutParams(this.getResources().getDimensionPixelSize(R.dimen.large),this.getResources().getDimensionPixelSize(R.dimen.large));
p.addRule(RelativeLayout.BELOW, cusViews.get(i-1).getId());
p.addRule(RelativeLayout.RIGHT_OF, cusViews.get(i-1).getId());
listParams.add(p);
}
relLayout.addView(cusViews.get(i), listParams.get(i));
}
However, what I want to do in the else statement is something like:
else{
LayoutParams p = new LayoutParams(this.getResources().getDimensionPixelSize(R.dimen.large),this.getResources().getDimensionPixelSize(R.dimen.large));
//Here I want to calculate cusView2Topmargin and cusView2Leftmargin based on the widths of the first or previosly positioned cusViews. But here the widths are 0 since they haven't been calculated yet.
p.topMargin = cusView2Topmargin; //Always zero
p.leftMargin = cusView2Leftmargin; //Always zero
listParams.add(p);
}
So the problem lies in that the widths of the cusViews are zero at the point I need them to calculate the layout parameters topMargin and leftMargin.
Unfortunately I cannot use the RelativeLayout's Rules for what I want to achieve. If there were some way to create rules like RelativeLayout.RIGHT_OF and RelativeLayout.BELOW I could do it like that. Is this possible?
Its not very clear what your goal is for this layout. It might well be possible to use a simple LinearLayout to get what you want.
If you want to size these from a database lookup then try simply adding each of the views, using addView() first, storing a reference to each, then go back and sett the margins to place them in the proper positions.

Place view inside FrameLayout in Android

I want to add a view inside a FrameLayout programmatically and to place it in a specific point within the layout with a specific width and height. Does FrameLayout support this? If not, should I use an intermediate ViewGroup to achieve this?
int x; // Can be negative?
int y; // Can be negative?
int width;
int height;
View v = new View(context);
// v.setLayoutParams(?); // What do I put here?
frameLayout.addView(v);
My initial idea was to add an AbsoluteLayout to the FrameLayout and place the view inside the AbsoluteLayout. Unfortunately I just found out that AbsoluteLayout is deprecated.
Any pointers will be much appreciated. Thanks.
The following example (working code) shows how to place a view (EditText) inside of a FrameLayout. Also it shows how to set the position of the EditText using the setPadding setter of the FrameLayout (everytime the user clicks on the FrameLayout, the position of the EditText is set to the position of the click):
public class TextToolTestActivity extends Activity{
FrameLayout frmLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
frmLayout = (FrameLayout)findViewById(R.id.frameLayout1);
frmLayout.setFocusable(true);
EditText et = new EditText(this);
frmLayout.addView(et,100,100);
frmLayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("TESTING","touch x,y == " + event.getX() + "," + event.getY() );
frmLayout.setPadding(Math.round(event.getX()),Math.round(event.getY()) , 0, 0);
return true;
}
});
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/frameLayout1"
android:layout_height="fill_parent" android:layout_width="fill_parent">
</FrameLayout>
</LinearLayout>
You can also add a margin around the newly added view to position it inside the FrameLayout.
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.main); // or some other R.id.xxx
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(0, metrics.heightPixels - 20, 0, 0);
View v = new View(context);
v.setLayoutParams(params);
frameLayout.addView(v);
This will position the FrameLayout 20 pixels from the bottom of the screen.
Edit: completed the example so it stands by itself. And oh, yes it does work.
It's true that with FrameLayout all children are pegged to the top left of the screen, but you still have some control with setting their padding. If you set different padding values to different children, they will show up at different places in the FrameLayout.
From the link Quinn1000 provided:
You can add multiple children to a FrameLayout, but all children are pegged to the top left of the screen.
This means you can't put your View at a specific point inside the FrameLayout (except you want it to be at the top left corner :-)).
If you need the absolute positioning of the View, try the AbsoluteLayout:
A layout that lets you specify exact locations (x/y coordinates) of its children. Absolute layouts are less flexible and harder to maintain than other types of layouts without absolute positioning.
As for setting the width and height of the View, also like Quinn1000 said, you supply the v.setLayoutParams() method a LayoutParams object, depending on the container you chose (AbsoluteLayout, LinearLayout, etc.)
The thread here on stackOverflow at
How do you setLayoutParams() for an ImageView?
covers it somewhat.
For instance:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
implies that you need to be defining a LinearLayout.LayoutParams (or in your case a FrameLayout.layoutParams) object to pass to the setLayoutParams method of your v object.
At
http://developer.android.com/reference/android/widget/FrameLayout.html
it almost makes it looks like you could ask your v to:
generateDefaultLayoutParams () via this method if you have not defined the parameters specifically.
But it's late, and those links are making my eyes bleed a little. Let me know if they nhelp any :-)

Categories

Resources