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 :-)
Related
I'd like to place a view on top of an existing view. The view I'm targeting is inside a LinearLayout, which resides in a FrameLayout.
I'm thinking there's a way to do this with RelativeLayout because I already have it partially working. I'd like to align the new view to the bottom-left or top-left (as the origin) and then offset X and Y to some precise value that I specify.
How can this be achieved?
Here's the idea:
public static void placeTextRelativeToBottomLeftOfViewAtXY(final FrameLayout layout, View component, int x, int y, String text) {
final TextView textView = new TextView(getContext());
textView.setId((int)System.currentTimeMillis());
final RelativeLayout relativeLayout = new RelativeLayout(getContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.setMargins(x, y, 0,0);
params.addRule(RelativeLayout.LEFT_OF, component.getId());
relativeLayout.setLayoutParams(params);
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
textView.setText("+500 points!");
textView.bringToFront();
relativeLayout.addView(textView, params);
layout.addView(relativeLayout);
}
Based on the additional information in comments, even if it is possible to overlap a different layouts inside a FrameLayout, those layouts will only be able to position their own children.
A RelativeLayout won't be able to position one of its child views relative to a view in a different sibling or parent Layout.
The way to go would be to flattern the heierarchy of Layouts, setting the root layout to a RelativeLayout or a ConstraintLayout.
ConstraintLayout is more flexible in terms of positioning views, but it is also more difficult to learn.
Here I am leaving an alternative to be used with RelativeLayout as the root view. The important items to look at are the setting of the LayoutParams which is sometimes a bit confussing.
The LayoutParams are set on the child view, but the class used depends on the parent view.
Also take in mind that to keep margins display independent you need to convert dp into pixels (for the sake of simplicity I haven't done that, but there are examples of how to do this here in SO).
It also uses View.generteViewId() go get an id for a view created dynamically.
To make it simple I included the reference View in the xml, but i could have also been created dynamically.
Layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rlContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tvCenterText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Texto estatico"
android:layout_centerInParent="true"/>
</RelativeLayout>
Main Activity
public class DynamicViewsActivity extends AppCompatActivity {
RelativeLayout rlContainer;
TextView centerText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamicviews);
rlContainer = findViewById(R.id.rlContainer);
centerText = findViewById(R.id.tvCenterText);
placeTextRelativeToBottomLeftOfViewAtXY(rlContainer, centerText, 100,10, "Hola");
}
public void placeTextRelativeToBottomLeftOfViewAtXY(final RelativeLayout layout, View component, int x, int y, String text) {
final TextView textView = new TextView(this);
textView.setId(View.generateViewId());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(x, y, x,y);
params.addRule(RelativeLayout.LEFT_OF, component.getId());
params.addRule(RelativeLayout.ALIGN_BASELINE, component.getId());
textView.setLayoutParams(params);
textView.setText(text);
layout.addView(textView);
}
}
In scrollview, if I add any view in middle, normally all the views below the added view scrolls downside. But I want to scroll the top views of added view to upside without disturbing the bottom views. Is it possible in scrollview , please help me ?
In the figure , If view 4 was added , then view 1 has to be scrolled upwards , without changing the positions of view 2 and view 3.
You can probably get the height of the view you are adding with and then scroll the scrollview manually that many pixels
scrollView.scrollBy(0, viewAdded.getHeight())
I've been wanting to try this question for quite some time, I finally got the chance today. The method is pretty simple (in fact, #dweebo already mentioned it earlier) - we move the ScrollView up as we add the view. For getting precise (and valid) dimensions when adding, we use a ViewTreeObserver. Here's the code you can get hints from:
// Getting reference to ScrollView
final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
// Assuming a LinearLayout container within ScrollView
final LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
// The child we are adding
final View view = new View(ScaleActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100);
view.setLayoutParams(params);
// Finally, adding the child
parent.addView(view, 2); // at index 2
// This is what we need for the dimensions when adding
ViewTreeObserver viewTreeObserver = parent.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
parent.getViewTreeObserver().removeOnPreDrawListener(this);
scrollView.scrollBy(0, view.getHeight());
// For smooth scrolling, run below line instead
// scrollView.smoothScrollBy(0, view.getHeight())
return false;
}
});
As you can see in the image, I can select the view and 3 ImageViews get added using "_root.addView(dragIcon);".
My problem is that the view is a simple view and not a ViewGroup , which means that in this picture i had to add the 3 images to the RelativeView Background "root.addView(dragIcon);" Instead of to the Green rectangle view shown in the image.
I'm pretty sure i can't change the View to a ViewGroup becuase a lot of methods (ex. onTouch) require a "View". I've tried casting the View to a ViewGroup "((ViewGroup) view).addView(dragIcon);" but that did't work.
You can make multiple Views in the app and drag them around, so I need to make the 3 images children to the specific parent View.
Any suggestions are appreciated, thanks!
Here is the part of the code that's relevant to this question...
_root = (ViewGroup)findViewById(R.id.root); //This is the background
_view = new View(this); //This is the View (Green in the Image)
private void selectView(final View view) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(final View view, final MotionEvent event) {
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView dragIcon, sizeIconTop, sizeIconBottom;
if (view.getTag(R.string.viewSelected) != "1") {
view.setBackgroundColor(0xFF00AA00);
view.setTag(R.string.viewSelected, "1");
double Ypos = view.getTranslationY() - view.getHeight() / 2;
// Set draggable (6*3 grid on the right)
dragIcon = new ImageView(MainActivity.this);
dragIcon.setImageResource(R.drawable.drabicon);
RelativeLayout.LayoutParams imgParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
imgParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imgParams.setMargins(0,0,30,0);
dragIcon.setLayoutParams(imgParams);
dragIcon.setTranslationY((float) Ypos + 70 + view.getHeight() / 2);
_root.addView(dragIcon); //Need to change from _root.addView to view.addView
// Set size top (White line at the top)
sizeIconTop = new ImageView(MainActivity.this);
sizeIconTop.setImageResource(R.drawable.resize);
RelativeLayout.LayoutParams stImgParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
stImgParams.setMargins(0,0,30,0);
stImgParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
sizeIconTop.setLayoutParams(stImgParams);
sizeIconTop.setTranslationY((float) Ypos + 99);
_root.addView(sizeIconTop); //Need to change from _root.addView to view.addView
// Set size bottom (White line at the bottom)
sizeIconBottom = new ImageView(MainActivity.this);
sizeIconBottom.setImageResource(R.drawable.resize);
RelativeLayout.LayoutParams sbImgParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
sbImgParams.setMargins(0,0,30,0);
sbImgParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
sizeIconBottom.setLayoutParams(sbImgParams);
sizeIconBottom.setTranslationY((float) Ypos + 93 + view.getHeight());
_root.addView(sizeIconBottom); //Need to change from _root.addView to view.addView
} else { //Ignore this part
//((ViewGroup) view).removeView(dragIcon);
//((ViewGroup) view).removeView(sizeIconTop);
//((ViewGroup) view).removeView(sizeIconBottom);
view.setBackgroundColor(0xFF00FF00);
view.setTag(R.string.viewSelected, "0");
}
}
});
Even though the question is a bit confusing, after analysing your code I figured out what you wanted to do.
Unfortunately, you have to choose whether to use a View (and not being able to attach the ImageViews) or using a ViewGroup (and handling the events yourself).
Since your View is a View, and your 3 ImageViews are also Views (means they are at the same level of usage), you can not add the last 3 to the first.
The rule is : You can add ViewGroups and Views to a ViewGroup, but you can not add Views or ViewGroups to a View. Views are supposed to be the elementary block of Android design.
void addView (View child)
Adds a child view. If no layout parameters
are already set on the child, the default parameters for this
ViewGroup are set on the child.
In my opinion, I would make View a ViewGroup and take care of the TouchEvents by myself.
Check this documentation/code regarding TouchEvents on ViewGroups
Let me know of your progress. Will be glad to help you.
Regards,
I'm having a difficulty adding buttons dynamically to a ScrollView. The code below is adding the buttons BUT there is no scroller.
If I'm putting the buttons directly in the XML (not dynamically) it's working and I can scroll down/up.
My view:
<ScrollView android:id="#+id/ScrollView01"
android:layout_width="264dp"
android:layout_height="match_parent"
android:fillViewport="true"
>
<LinearLayout
android:id="#+id/buttons"
android:layout_width="264dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:scrollbars="vertical"
>
** HERE THE BUTTONS SHOULD BE ADDED DYNAMICALLY **
</LinearLayout>
</ScrollView>
The code which adding buttons:
// create new button
final Button newbutton = new Button(this);
// set background color
newbutton.setBackgroundColor(Color.GRAY);
// set width and height
newbutton.setWidth(50);
newbutton.setHeight(20);
// set position
newbutton.setY(((float)numOfButton*20)+20);
newbutton.setX(100);
// set text
newbutton.setText(Integer.toString(numOfButton));
// create patameter
final LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
//set listener
android.view.View.OnClickListener buttonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// make all the DrawView invisible
for(View view : comments){
view.setVisibility(View.INVISIBLE);
}
// set the chosen comment visible
comments.get(numOfButton).setVisibility(View.VISIBLE);
boardsHandler.setCurrenBoard(numOfButton);
}};
newbutton.setOnClickListener(buttonListener);
// creating a thread to add button
buttons.post(new Runnable() {
#Override
public void run() {
buttons.addView(newbutton, p);
}
});
Is it something with the LinearLayout.LayoutParams p ?
Thanks!
Try following code
first do
LinearLayout myContainer = findViewById(R.id.layoutId);
When you set parameters for a view, they need to correspond to the parent view for your widget.
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
finally add button as you are doing.
try and tell if it works
Setting X and Y position will not work. The LinearLayout layouts it's children vertically or horizontally, only taking their width/height into account.
Besides this -- have you tried calling buttons.invalidate() after buttons.addView(...). This should refresh the layout and should show your newbutton.
This is a rather old post but I found it quickly when doing research on that kind of problem. So I'll post am answer anyway, maybe it'll be of help to anyone..
I had a similar problem with a relative layout to which buttons were added dynamically. I found a workaround in defining the layout's size manually when adding the buttons. For your case, adding the line
buttons.getLayoutParams().height = numOfButton*20+40;
after
buttons.addView(newbutton, p);
might help, though it's probably not the best solution.
I thought my mistake was using the RelativeLayout at all, but since you appear to have the same problem...
Ever thought of using a table layout?
I have a number of elements in a ListView that scroll off the screen.
I would like there to be blank space at the end of the View. That is, the user should be able to scroll past the last element such that the last element is in the middle of the viewport.
I could use an OverScroller, but I think that would only enable the View to have a bouncy effect like one often sees on the iPhone.
Is there something I might have overlooked?
The scrolled-to-the-botton screen should look something like this:
The accepted answer is too complicated, and addFooterView is not for this kind of thing. The proper and simpler way is to set the paddingTop and paddingBottom, and you need to set clipToPadding to "false". In your list view or grid view, add the following:
android:paddingTop="100dp"
android:paddingBottom="100dp"
android:clipToPadding="false"
You'll get blank space at the top and the bottom that moves with your finger scroll.
Inflate any layout of your choice (this could be an XML of and ImageView with no drawable and with set height and width of your choice)
Measure the screen height and create new LayoutParams and set the height of it to 1/2 of the screen height
Set the new layout params on your inflated view
Use the ListView's addFooterView() method to add that view to the bottom of your list (there is also an addHeaderView())
Code to measure screen height
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int screenHeight = display.getHeight();
Code to set half screen height:
View layout = inflater.inflate(R.layout.mylistviewfooter, container, false);
ViewGroup.LayoutParams lp = layout.getLayoutParams();
lp.height = screenHeight/2;
layout.setLayoutParams(lp);
myListView.addFooterView(layout);
An Aside:
When you add a footer or header view to any listview, it has to be done before adding the adapter. Also, if you need to get your adapter class after doing this you will need to know calling the listview's adapter by getAdapter() will return an instance of HeaderViewListAdapter in which you will need to call its getWrappedAdapter method
Something like this :
MyAdapterClassInstance myAdapter = (MyAdapterClassInstance) ((HeaderViewListAdapter) myListView.getAdapter()).getWrappedAdapter();
this 100% works.
in adapter set your code like this
//in getCount
#Override
public int getCount() {
return ArrayList.size()+1;
}
//in getview make your code like this
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.yourlayout, null);
if(i<getCount()-1) {
//your code
}
else{
ViewGroup itemContainer =(ViewGroup) view.findViewById(R.id.container);
itemContainer.setVisibility(View.INVISIBLE);
}
Return view;
}
if you have multiple listviews in your app, create an xml of a footer, something like this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:minHeight="200dp"
android:layout_width="match_parent"
android:layout_height="200dp"></LinearLayout>
and then in the code, use this:
listView.addFooterView(LayoutInflater.from(getActivity()).inflate(R.layout.empty200, null));
This do the job in a simple way
android:paddingBottom="100dp"
android:clipToPadding="false"
Try the followings:
View footer = new View(getActivity());
footer.setLayoutParams( new AbsListView.LayoutParams( LayoutParams.FILL_PARENT, 100 ));
// 100 is the height, you can change it.
mListView.addFooterView(footer, null, false);