".addView()" for simple views - android

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,

Related

android scrollview scroll to top direction when new view added

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;
}
});

Larger bounds for touch feedback of a View

I am looking for a solution to have larger bounds for selector of an Android view.
Imagine that View is a rectangle view. When user click on the view touch feedback that will be shown is a circle pretty larger than view bounds.
Do you know a good approach to build such an idea?
There is no way how to do that in view's bounds.(I think ). You can implement it by making visual action on parent background view.
ImageButton im = (ImageButton) findViewById(R.id.ur_btn);
im.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float x = im.getX();
float y = im.getY();
}
});
}
private void addCircleBehindRectangle(int x, int y){
RelativeLayout parent = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv = new ImageView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(x, y);
//optional margin l/r
params.leftMargin = 50;
params.topMargin = 60;
parent.addView(iv, params);
}
I hope it helps a little bit. Good luck
If you want to show a view outside of its clipping area, you need to enable this in its parent container (any layout which derives from ViewGroup):
ViewGroup.clipChildren
Another way is increase/decrease paddings of the clicked view itself.

How do I fit an exact number of ListView items on screen?

I would like the rows in a ListView to be sized so that exactly six of them can fit on the screen. For that, I would need to know how much vertical space is available to the ListView (not the whole screen). However, no measuring can be done in onCreate() since no views have been rendered yet.
If I make measurements after rendering, the ListView might be drawn and then resized, which may be distracting. What is the smartest way to establish the necessary row height before rendering the ListView?
in onCreate you can get the height of your screen and divide by 6.
Now in your getView you get the reference of the top layout for each item, suppost you have named it's id to root and i.e it's a LinearLayout.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null){ some inflate }
LinearLayout root = (LinearLayout) view.findViewById(R.id.root);
LayoutParams lp = root.getLayoutParams();
lp.height = screenHeight/6;
root.setLayoutParams(lp);
....
return view;
}
Yes, this assumes the ListView is in fullscreen.
If you have other layouts, you will have to get those height into account.
Then your height will be: int heightForEachItem = (screenHeight - otherlayoutsHeightTogether) / 6;
Turns out that the earliest you can measure a ListView is in the onGlobalLayout() callback.
Here is my example.
params = new AbsListView.LayoutParams(-1,-1);
listview.getViewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){ //this is called just before rendering
params.height = listview.getHeight()/6; // this is what I was looking for
listview.getViewTreeObserver.removeOnGlobalLayoutListener(this); // this is called very often
}
adapter = new ArrayAdapter<...>(int position, ...){
#Override
public View getView(...){
LinearLayout item = new LinearLayout(context);
item.setLayoutParams(params);
// add text, images etc with getItem(position) and item.addView(View)
return item;
}
}
listview.setAdapter(adapter);

how to set textview dynamically according to numbers of strings

I am getting list of phone companies from web service and i have to set it to textview but the problem is i am not getting alignment as above image.How to achieve it.
From what I understand, you want to add text views one beside the other, but when they overflow (go out of the screen) the next text view should be placed in the next line.
Doing this is not trivial. Implementing something like this (optimally and correctly) requires understanding of how android draws views (onMeasure and onLayout). However if you do not care about efficiency that much (mainly because you are going to do it only for a small portion of the view) then here is my quick hack:
mContainer = (RelativeLayout) findViewById(R.id.container);
// first layout all the text views in a relative layout without any params set.
// this will let the system draw them independent of one another and calculate the
// width of each text view for us.
for (int i = 0; i < 10; i++) {
TextView tv = new TextView(getApplicationContext());
tv.setText("Text View " + i);
tv.setId(i+1);
tv.setPadding(10, 10, 20, 10);
mContainer.addView(tv);
}
// post a runnable on the layout which will do the layout again, but this time
// using the width of the individual text views, it will place them in correct position.
mContainer.post(new Runnable() {
#Override
public void run() {
int totalWidth = mContainer.getWidth();
// loop through each text view, and set its layout params
for (int i = 0; i < 10; i++) {
View child = mContainer.getChildAt(i);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// this text view can fit in the same row so lets place it relative to the previous one.
if(child.getWidth() < totalWidth) {
if(i > 0) { // i == 0 is in correct position
params.addRule(RelativeLayout.RIGHT_OF, mContainer.getChildAt(i-1).getId());
params.addRule(RelativeLayout.ALIGN_BOTTOM, mContainer.getChildAt(i-1).getId());
}
}
else {
// place it in the next row.
totalWidth = mContainer.getWidth();
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.BELOW, mContainer.getChildAt(i-1).getId());
}
child.setLayoutParams(params);
totalWidth = totalWidth - child.getWidth();
}
mContainer.requestLayout();
}
});
Basically, I let the system do the layout and measurement for me in the first round(s) of drawing. Then using the widths of each text view now available, I reset the layout params based on the wrapping logic and do the layout again.
Try it with text of different size, it will auto adjust. I would say this solution is pretty hacky but it works. If you are not satisfied with it take a look at this.
use
android:textAlignment="textStart"

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