android scrollview scroll to top direction when new view added - android

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

Related

How to check if there is space available before inflating a new view in a LinearLayout?

I have a fragment at the bottom of my Activity which can be filled with words(views). This is a image of the fragment:
Between the blue buttons you can inflate views by clicking on a item in an GridView that is above this fragment. Everytime I click an item a view with text: "Test" is being added. It starts left with inflating views untill it doesn't fit in the LinearLayout anymore.
When the LinearLayout is full, it looks like this:
When the layout looks full, you still can inflate views but you don't see them being added anymore.
The most right purple view you can see on the image above has a bigger height then the rest because it doesn't fit anymore.
I want to check if there is enough space in the LinearLayout to inflate a new view.
This is the code that inflates the views in the LinearLayout:
public void inflateAllViews(){
LayoutInflater inflaterr = (LayoutInflater) MainApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
linearLayout.removeAllViews();
ArrayList<WordTile> wordsToInflate = WordManager.getWordsToInflate();
for(WordTile WordTile : wordsToInflate){
View word = inflaterr.inflate(R.layout.word, null);
final TextView textView = (TextView)word.findViewById(R.id.text_word);
textView.setText(WordTile.getTitle());
linearLayout.addView(word);
}
}
But I need to check whether the view can be added or not because there is no space left. Because in the background you can add unlimited views to the LinearLayout.
I tried to find a way to calculate the widths of the inflated views. The only thing I found was this:
ViewTreeObserver vto = word.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Log.d("TEST", "Height = " + word.getHeight() + " Width = " + word.getWidth());
widthOfChildren += word.getWidth();
System.out.println("widthofchildren:" + widthOfChildren);
ViewTreeObserver obs = word.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
}
});
The code works and prints the width I need for every view. But I can't use the width outside of the OnGlobalLayoutListener....
Does anyone have a solution to my problem?
EDIT:
The problem is not the width of the LinearLayout because I know that width, it is the widths of the views that are in the LinearLayout. The LinearLayout has a standard width which doesn't change.

Adding views dynamically in a for loop results in haphazard positioning - Android

I am adding views dynamically to a relative layout (let's say container) in a for loop. There is some thing strange I am noticing. When adding rows one below the other in a relative layout in a for loop, I see that the first time a few of the views are overlapping. But when I lock and unlock the screen, I can see that the views are placed correctly.
Should I be aware of something when adding views dynamically to a relative layout?
Edit
I have found a solution as to how to get rid of this (please check my answer). But I would be more than glad to accept an answer that analyses this problem and tells me why this happens.
I have simplified to code and the comments should give a good idea as to what I am doing.
int prev_id=ID_OF_THE_ELEMENT_ABOVE;
/*Empty RelativeView with width and height as MATCH_PARENT and WRAP_CONTENT respectively*/
RelativeLayout container=(RelativeLayout) findViewById(R.id.container);
while(ThereIsData){
/*GET THE DATA HERE THAT HAS TO BE ASSIGNED TO EACH TEXTVIEW*/
...
/* ADD TEXTVIEW #1 below prev_id/
...
...
/*ADD TEXTVIEW #2 (WITH BASELINE OF TEXTVIEW#
...
...
/*TEXTVIEW #3 (BELOW TEXTVIEW#1)*/
...
...
/*TEXTVIEW #4 (BELOW TEXTVIEW#2)*/
...
...
/*ASSIGN THE ID OF TEXTVIEW#3 TO prev_id SO THAT
IN THE NEXT ITERATION TEXTVIEW#1 CAN USE prev_id
*/
prev_id=ID(TEXTVIEW#2);
/*ADD TEXTVIEWS CREATED IN THIS ITERATION*/
container.addView(TEXTVIEW#1);
container.addView(TEXTVIEW#2);
container.addView(TEXTVIEW#3);
container.addView(TEXTVIEW#4);
}
It is due to the fact that you are having a RelativeLayout with height as WRAP_CONTENT, and adding a view doesn't refresh the whole container at that time.. so as you answered you can add a line to measure the dimensions explicitly or invalidate the view to recreate it completely.
In any case LinearLayout would be better to opt-for as it will automatically arrange the children in horizontal or vertical manner and you can even add the new view in any place other than last position and it will automatically be updated..
I used to struggle against common issues a year ago, when I was working on a library for dynamically creating layouts from XML files (as Android does not support this). So when you dynamically add views to a RelativeLayout you have to take in mind a few things:
Create the container View (in this case the RelativeLayout)
Create all views without assigning any layout parameters.
Add all child views to the container.
Iterate over the container's children and populate each child's layout parameters. This is needed because when the relational constraints are applied an Excpetion is thrown if the relative View is missing (was not previously added to the container).
This is an example code taken from the project I used to work on. Take in mind that it is just a single part so it contains references to classes that are not defined in the Android API. I am sure it will give you the basic idea of dynamically creating RelativeLayot:
private void setChildren(RelativeLayout layout, T widget,
InflaterContext inflaterContext, Context context,
Factory<Widget, View> factory) {
List<Widget> children = widget.getChildren();
if (Utils.isEmpty(children))) {
return;
}
// 1. create all children
for (Widget child : children) {
View view = factory.create(inflaterContext, context, child);
layout.addView(view);
}
// 2. Set layout parameters. This is done all children are created
// because there are relations between children.
for (Widget child : children) {
try {
View view = ViewIdManager.getInstance().findViewByName(layout, child.getId());
if (view != null) {
populateLayoutParmas(child, view);
}
} catch (IndexNotFoundException e) {
Log.e(LOG_TAG, "Cannot find a related view for " + child.getId(), e);
}
}
}
I have not yet found the answer to why this is happening. But I have found a solution. After adding each row in the loop, call container.measure(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
This seems to solve the problem. But I really think that container.addView() should also be calling measure().
/*ADD TEXTVIEWS CREATED IN THIS ITERATION*/
container.addView(TEXTVIEW#1);
container.addView(TEXTVIEW#2);
container.addView(TEXTVIEW#3);
container.addView(TEXTVIEW#4);
//---------------------------------------------------------------------
container.measure(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
//Declare globally
LinearLayout[] layout;
ImageView[] imageView1;
ImageView[] imageView2;
ImageView[] imageView3;
// Initialize your layout. It would be RelativeLayout too. Just reference to it.
LinearLayout ll = (LinearLayout) findViewById(R.id.mylinear);
// set listview row size as your demand
layout = new LinearLayout[200];
imageView1 = new ImageView[200];
imageView2 = new ImageView[200];
imageView3 = new ImageView[200];
for (int i = 0; i < 200; i++) {
layout[i] = new LinearLayout(this);
layout[i].setBackgroundResource(R.drawable.book_shelf);
// layout[i].setLayoutParams(new
// LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.FILL_PARENT,
// 120));
layout[i].setLayoutParams(new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.FILL_PARENT, 220));
imageView1[i] = new ImageView(this);
imageView2[i] = new ImageView(this);
imageView3[i] = new ImageView(this);
imageView1[i].setLayoutParams(new LinearLayout.LayoutParams(0, 200,
0.33f));
imageView1[i].setPadding(0, 20, 0, 0);
imageView1[i].setImageResource(R.drawable.bibid_one_bankim);
imageView2[i].setLayoutParams(new LinearLayout.LayoutParams(0, 200,
0.33f));
imageView2[i].setPadding(0, 20, 0, 0);
imageView2[i].setImageResource(R.drawable.bibid_two_bankim);
imageView3[i].setLayoutParams(new LinearLayout.LayoutParams(0, 200,
0.33f));
imageView3[i].setImageResource(R.drawable.dena_pawna);
imageView3[i].setPadding(0, 20, 0, 0);
layout[i].setId(i);
layout[i].setClickable(true);
final int j = i;
layout[i].addView(imageView1[i]);
layout[i].addView(imageView2[i]);
layout[i].addView(imageView3[i]);
ll.addView(layout[i]);
}
}
Try adding your views in vertical Linear Layout.
Following link might help you
http://www.myandroidsolutions.com/2012/06/19/android-layoutinflater-turorial/
Inflate your layout in for loop.

Programmatically add items to scrollview top, but should not scroll to top

I have scrollview with child LinearLayout . I am adding data programmaticaly to it. When i add some data to top of linearlayout it automatically scrolls to top element. But i want something like , user reaches top -> scrolls upside to load previous data ->add data to linearlayout top but should not get focus, after addition complete , if user scrolls then and then only it should display .
How to achieve this?
Well I thought of a way and it works almost perfectly.
I have a LinearLayout (llCommunicationsLayout) inside a ScrollView (svCommunications) .
I inflate a new LinearLayout, I'm going to add views to the top of this new LinearLayout and then add this new layout to the LinearLayout inside the ScrollView.
This is the new layout:
final LinearLayout wrapperLayout = (LinearLayout) mInflater.inflate(R.layout.empty_layout, null);
I add my views to the 0'th position of this layout.
wrapperLayout.addView(view, 0);
After all the views are added into the wrapperLayout, I add the wrapperLayout into the llCommunicationsLayout (the one inside my ScrollView)
llCommunicationsLayout.addView(wrapperLayout, 0);
After this, I calculate their heights after the wrapperLayout is on screen (has a measurable height)
wrapperLayout.post(new Runnable() {
#Override
public void run() {
int wrapperHeight = wrapperLayout.getHeight();
int svHeight = svCommunications.getHeight();
int scrollHeight = Math.abs(svHeight - wrapperHeight);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int displayHeight = displaymetrics.heightPixels / 4;
svCommunications.scrollTo(0, (scrollHeight + displayHeight));
}
});
Here, I get both the newly added layout's and the ScrollView's heights.
I calculate their difference, add the 1/4 of the height of the screen of my device and scroll it, voila!
It's not perfect, but after the layouts are added, it no longer scrolls to the top of the screen. Experiment with the displayHeight for different results.
Hope this helps someone out.
You can grab the current view which is on top of your LinearLayout then add new content to your LinearLayout and then scroll back to view which was previously on top. The code would be something like:
public void addViewsOnTop(List<View> views) {
final View currentViewOnTop = (linearLayout.getChildCount() > 0) ? linearLayout.getChildAt(0) : null;
// Add Views. Note that views will appear in reverse order
for(View view : views) {
linearLayout.addView(view, 0);
}
// Scroll back to view which was on top
if(currentViewOnTop != null) {
new Handler().post(new Runnable() {
#Override
public void run() {
scrollView.scrollTo(0, currentViewOnTop.getBottom());
}
});
}
}
Solved....
Try this, worked for me ,
lv_chat.setAdapter(adapter);
lv_chat.setSelection(somePreviousPosition);

How to check whether ScrollView is scrollable

I was wondering, how to check whether the current ScrollView is scrollable? It seems that, there isn't public method called canScroll or isScrollable in ScrollView.
Scrollable : You can move the ViewGroup inside the ScrollView up and down, and the scroll bar will be visible when you move it up and down. So, if there is only little rows in the ScrollView, and they can fit inside single screen, ScrollView is not scrollable then.
You can do some little math to calculate the views raw height and the height of the content. If the difference of this heights is < 0 the view is scrollable.
To calculate the raw height you can use View.getMeasuredHeight().
Because ScrollView is a ViewGroup and has max one child, get the height of that child with ViewGroup.getChildAt(0).getHeight();
Use a ViewTreeObserver to get the heights, because it will be called at the moment the layout / view is changing the visibility, otherwise the heights could be 0.
ScrollView scrollView = (ScrollView)findViewById(R.id...);
ViewTreeObserver observer = scrollView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int viewHeight = scrollView.getMeasuredHeight();
int contentHeight = scrollView.getChildAt(0).getHeight();
if(viewHeight - contentHeight < 0) {
// scrollable
}
}
});
scrollView.viewTreeObserver
.addOnGlobalLayoutListener {
val isScrollable = scrollView.canScrollVertically(1)
}
I think I might be missing something, but shouldn't it be as simple as checking if
scrollView.getHeight() >= parentView.getMeasuredHeight()
you might actually need: scrollView.getChildAt(0).getHeight() and/or parentView.getHeight() instead, but the idea is the same.

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

Categories

Resources