Rectangle 27 0

In order to refresh a table layout (TableLayout) I ended up having to use the recursive approach mentioned above to get all the children's children and so forth.

My situation was somewhat simplified because I only needed to work with LinearLayout and those classes extended from it such as TableLayout. And I was only interested in finding TextView children. But I think it's still applicable to this question.

The final class runs as a separate thread, which means it can do other things in the background before parsing for the children. The code is small and simple and can be found at github: https://github.com/jkincali/Android-LinearLayout-Parser

Android - get children inside a View? - Stack Overflow

android view
Rectangle 27 0

It's easy to do that by defining a custom view group as follows:

All children views of MyViewContainer will be shown in grey. :-)

android - How to apply a color filter to a view with all children - St...

android view colors filter
Rectangle 27 0

You can expand it in getGroupView in your custom adapter:

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    View v = super.getGroupView(groupPosition, isExpanded, convertView, parent);
    ExpandableListView mExpandableListView = (ExpandableListView) parent;
    mExpandableListView.expandGroup(groupPosition);
    return v;
}

@DavidLawson: yep, my sollution is fixed-expand them. If you wana expand them and they are clickable, you have to handle that where ExpandableListView is created, like Drejc's sollution.

android - Expand all children in expandable list view - Stack Overflow

android expandablelistview
Rectangle 27 0

Jin35's answer has a serious problem: getChildCount() changes value over the iterations because we are removing the children.

This should be a better solution:

while (getChildCount() > 0) {
    View v = getChildAt(0);
    removeViewAt(0);
    llContainer.addView(v);
}

android: how to add children from an xml layout into a custom view - S...

android android-layout android-xml android-custom-view android-resources
Rectangle 27 0

I just encountered this problem. I figured out it was due to the new hardware acceleration support in 3.0+ The way I solved it was using View#setLayerType and using LAYER_TYPE_SOFTWARE. In order to continue targeting API level 8 I used reflection to call this method on supporting android platforms. This solved the issue and now my custom ViewGroup draws properly when the children are invalidated.

I don't know if this will solve your problem exactly but it may help others who are also perplexed by this issue.

try {
    Method method =
            CustomViewGroup.class.getMethod("setLayerType", new Class[] { Integer.TYPE, Paint.class });
    // 0x1 == LAYER_TYPE_SOFTWARE
    method.invoke(this, new Object[] { Integer.valueOf(0x1), null });
} catch(SecurityException e) {
    Log.e(TAG, "reflectSetLayerType", e);
} catch(NoSuchMethodException e) { // don't care
} catch(IllegalArgumentException e) {
    Log.e(TAG, "reflectSetLayerType", e);
} catch(IllegalAccessException e) {
    Log.e(TAG, "reflectSetLayerType", e);
} catch(InvocationTargetException e) {
    Log.e(TAG, "reflectSetLayerType", e);
}

android - How do I trigger the redraw of a parent View when any of it'...

android user-interface android-layout android-widget
Rectangle 27 0

If you not only want to get all direct children but all children's children and so on, you have to do it recursively:

private ArrayList<View> getAllChildren(View v) {

    if (!(v instanceof ViewGroup)) {
        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        return viewArrayList;
    }

    ArrayList<View> result = new ArrayList<View>();

    ViewGroup vg = (ViewGroup) v;
    for (int i = 0; i < vg.getChildCount(); i++) {

        View child = vg.getChildAt(i);

        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        viewArrayList.addAll(getAllChildren(child));

        result.addAll(viewArrayList);
    }
    return result;
}

To use the result you could do something like this:

// check if a child is set to a specific String
    View myTopView;
    String toSearchFor = "Search me";
    boolean found = false;
    ArrayList<View> allViewsWithinMyTopView = getAllChildren(myTopView);
    for (View child : allViewsWithinMyTopView) {
        if (child instanceof TextView) {
            TextView childTextView = (TextView) child;
            if (TextUtils.equals(childTextView.getText().toString(), toSearchFor)) {
                found = true;
            }
        }
    }
    if (!found) {
        fail("Text '" + toSearchFor + "' not found within TopView");
    }

This call is not save, as e.g. child can be of type View and not of ViewGroup, so the recursive call of getAllChildren could cause an exception, as the cast fails. So you should add a if (!(v instanceof ViewGroup)) return; before the cast

Small suggestion: replace your for loop with for (int i = 0, n = vg.getChildCount(); i < n; i++) On Android, accessing local variables instead of calling a method tends to be much faster. This way, a method is called only once per view group and then on subsequent runs a local variable is used.

I changed the code because of the suggestion of Phil Diegmann. Hope this helps. Works for me.

Cool. I would only suggest adding a boolean 'includeViewGroups' and only if it is true, iewArrayList.add(v); This is useful for iterating in an Adapter (and I need only the leafs). Thanks!

Android - get children inside a View? - Stack Overflow

android view
Rectangle 27 0

have a look this may be useful to you:

public class MainActivity extends Activity {

@Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
  ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
  myPager.setAdapter(adapter);
  myPager.setCurrentItem(0);
 }

 private int imageArra[] = { R.drawable.gallery_photo_1, R.drawable.gallery_photo_2,
   R.drawable.gallery_photo_3, R.drawable.gallery_photo_5,
   R.drawable.gallery_photo_6, R.drawable.gallery_photo_7,
   R.drawable.gallery_photo_8, R.drawable.ic_launcher };

}

and ViewPagerAdapter:

public class ViewPagerAdapter extends PagerAdapter {

Activity activity;
int imageArray[];

public ViewPagerAdapter(Activity act, int[] imgArra) {
    imageArray = imgArra;
    activity = act;
}

public int getCount() {
    return imageArray.length;
}

public Object instantiateItem(View collection, int position) {
     ImageView view = new ImageView(activity);
      view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
        LayoutParams.FILL_PARENT));
      view.setScaleType(ScaleType.FIT_XY);
      view.setBackgroundResource(imageArray[position]);
      ((ViewPager) collection).addView(view, 0);
    return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);
}

@Override
public Parcelable saveState() {
    return null;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<android.support.v4.view.ViewPager
    android:id="@+id/myfivepanelpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" >

    </ImageView>
</android.support.v4.view.ViewPager>

</LinearLayout>

sadly, can't even get it to work with this

it is working fine i tried already now i attached xml file also once you can try...

hi again, I tried it and it almost worked, but as soon as I swipe to go to the next picture, the application crashes. why would that be?

It does not put the images side by side but they are all in the same place

what is your requirement do you want to view all images on screen at a time or you want to view single single image by swpping images?

android - Using viewpager for scrolling children inside a view - Stack...

android android-viewpager swipe
Rectangle 27 0

I guess what you search is android:baselineAligned="false", this will avoid that the text are on the same baseline and the buttons will start at the same y position on the screen.

android:baselineAligned="false"

However if you also want that both buttons are equal sized try this layout example:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:baselineAligned="false">

    <Button
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="aaaaa"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="bbbbbbb bbbbbbbb bbbbbbbb bbbbbbbbbbbb bbbbbb"/>

</LinearLayout>

So we can have wrap_content on parent and match_parent on the children? Strange but nice. Thanks.

Yes out of the perspective of the child it will match the parent size

android - Children views having equal height - Stack Overflow

android android-layout android-linearlayout android-xml
Rectangle 27 0

Jin35's answer has a serious problem: getChildCount() changes value over the iterations because we are removing the children.

This should be a better solution:

while (getChildCount() > 0) {
    View v = getChildAt(0);
    removeViewAt(0);
    llContainer.addView(v);
}
StackOverflowException

@howettl If you're getting a StackOverflowException chances are you did what I did and tried to move a view into one of its children.

android: how to add children from an xml layout into a custom view - S...

android android-layout android-xml android-custom-view android-resources
Rectangle 27 0

...
private void init() {
  View child1 = findViewById(R.id.child1);
}
...

or if you have a reference to a view:

...
private void init(View root) {
  View child2 = root.findViewById(R.id.child2);
}

I don't have access to ids, the UI is generated via code, I am writing automation using robotium, so things I can do are limited

Android - get children inside a View? - Stack Overflow

android view
Rectangle 27 0

Place your relative layout inside a LinearLayout. And place that LinearLayout in a ScrollView

<ScrollView>
 <LinearLayout>
  <RelativeLayout>
    ...
    ...
    ...
  </RelativeLayout>
 </LinearLayout>
</ScrollView>

I am not sure why this works, but it does

@AkshatAgarwal because scrollview can only have one direct child.

android - how to make a relative layout scrollable when it has many ch...

android android-layout android-xml android-scrollview
Rectangle 27 0

You are correct about the fact that only layouts (ViewGroups) can contain Views, and Views itself can not.

Instead of making a custom View, you can make a custom ViewGroup. In there you can add the Views you need, like the ImageViews and the others you mention (Buttons, EditText, etc).

can I assign to custom layout such properties as to my custom view? For example, can onTouchlistener be overrided for custom layout?

Yes, that is possible. You need to watch out though that if you add a button, you might not want the ViewGroup to use the touch. More info here: developer.android.com/training/gestures/viewgroup.html

android - Custom view with children inside it(buttons, edittexts, etc....

android android-custom-view
Rectangle 27 0

for(int i=0; i<((ViewGroup)v).getChildCount(); ++i) {
    View nextChild = ((ViewGroup)v).getChildAt(i);
}

Android - get children inside a View? - Stack Overflow

android view
Rectangle 27 0

Here is a suggestion: you can get the ID (specified e.g. by android:id="@+id/..My Str..) which was generated by R by using its given name (e.g. My Str). A code snippet using getIdentifier() method would then be:

public int getIdAssignedByR(Context pContext, String pIdString)
{
    // Get the Context's Resources and Package Name
    Resources resources = pContext.getResources();
    String packageName  = pContext.getPackageName();

    // Determine the result and return it
    int result = resources.getIdentifier(pIdString, "id", packageName);
    return result;
}

From within an Activity, an example usage coupled with findViewById would be:

// Get the View (e.g. a TextView) which has the Layout ID of "UserInput"
int rID = getIdAssignedByR(this, "UserInput")
TextView userTextView = (TextView) findViewById(rID);

Android - get children inside a View? - Stack Overflow

android view
Rectangle 27 0

I'm just going to provide this answer as an alternative @IHeartAndroid's recursive algorithm for discovering all child Views in a view hierarchy. Note that at the time of this writing, the recursive solution is flawed in that it will contains duplicates in its result.

For those who have trouble wrapping their head around recursion, here's a non-recursive alternative. You get bonus points for realizing this is also a breadth-first search alternative to the depth-first approach of the recursive solution.

private List<View> getAllChildrenBFS(View v) {
    List<View> visited = new ArrayList<View>();
    List<View> unvisited = new ArrayList<View>();
    unvisited.add(v);

    while (!unvisited.isEmpty()) {
        View child = unvisited.remove(0);
        visited.add(child);
        if (!(child instanceof ViewGroup)) continue;
        ViewGroup group = (ViewGroup) child;
        final int childCount = group.getChildCount();
        for (int i=0; i<childCount; i++) unvisited.add(group.getChildAt(i));
    }

    return visited;
}

A couple of quick tests (nothing formal) suggest this alternative is also faster, although that has most likely to do with the number of new ArrayList instances the other answer creates. Also, results may vary based on how vertical/horizontal the view hierarchy is.

Android - get children inside a View? - Stack Overflow

android view
Rectangle 27 0

The simple approach would be to work on simplifying and flattening the current view hierarchy and maybe you'll be able to make the measuring and drawing process much cheaper(or decent at least). You didn't posted a layout so there isn't something specific to say, I've seen you mentioned RelativeLayouts in RelativeLayouts, maybe you could remove one and move the views up one level(even with the expense of adding other helper views), every level counts(especially with nesting RelativeLayouts). You probably know already but the merge and include tags in layouts could prove quite useful.

RelativeLayout being in the standard SDK was built as a general widget so it most likely can't achieve the performance of a custom designed layout. It would make much more sense to make your current layouts extending RelativeLayout to extend ViewGroup and implement the measuring and layout of children manually especially as you probably know the use case scenarios in your apps(for example a RelativeLayout always needs to handle all the size constraint cases it could be in, your custom layout on the other hand could handle this much faster if you know that the custom view will have a certain size).

Related to a completely custom drawn view, it's an option but it depends on the complexity of your layout.

android - Performance: ViewGroup with Children VS. custom drawn View -...

android android-layout custom-controls android-view android-custom-view
Rectangle 27 0

Why don't you just add all the children to the LinearLayout from your ScrollLayout? This should be done in the onFinishInflate() method.

for (int i = 0; i<getChildCount(); i++)
{
    View v = getChildAt(i);
    removeViewAt(i);
    llContainer.addView(v);
}

When you write your structure in the XML file - all inner views are children of your custom layout. Just replace it to LinearLayout.

i tried as you say, but the child count is always 0

super.removeAllViews();

the same without that line... could it be because I placed your code inside the init()?

onFinishInflate()

I suppose that when android starts inflating views it goes from parents to children - and when you are in constructor of custom view - children does not exist yet.

android: how to add children from an xml layout into a custom view - S...

android android-layout android-xml android-custom-view android-resources
Rectangle 27 0

you need to inflate your layout into dialog's view and retrieve TextViews/EditTexts from the inflated view:

LayoutInflater li = getLayoutInflater();// LayoutInflater.from(getBaseContext());
View view = li.inflate(R.layout.your_dialog_layout, null);

EditText email = (EditText) view.findViewById(R.id.etDialogEmail);
TextView title = (TextView) view.findViewById(R.id.tvDialogTitle);
//and your other stuff....

AlertDialog.Builder bldr = new AlertDialog.Builder(getBaseContext());
bldr.setView(view);
AlertDialog diag = bldr.create();

layout - how to bind a view to alertdialog and use the children in thi...

android layout view alertdialog
Rectangle 27 0

I am using a expandable listview inside viewpager. For a page there will be only on group . While click on it ,it will show the child view . While swiping the page .The values will be changed. The problem i am facing now is . I m trying to make the group as expanded by default. I tried the below code but after this getChildView() is not calling and it also not expanding my group. Help please.

public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    View v = super.getGroupView(groupPosition, isExpanded, convertView, parent);
    ExpandableListView mExpandableListView = (ExpandableListView) parent;
    mExpandableListView.expandGroup(groupPosition);
    return v;
}
mExpandableListView.expandGroup(0);
list.setAdapter(new ProductExpandableAdapter(activity, subMenuList,position));
list.expandGroup(0);

This looks to be a related question, and not actually an answer.

android - Expand all children in expandable list view - Stack Overflow

android expandablelistview
Rectangle 27 0

Why don't you just add all the children to the LinearLayout from your ScrollLayout? This should be done in the onFinishInflate() method.

for (int i = 0; i<getChildCount(); i++)
{
    View v = getChildAt(i);
    removeViewAt(i);
    llContainer.addView(v);
}

When you write your structure in the XML file - all inner views are children of your custom layout. Just replace it to LinearLayout.

i tried as you say, but the child count is always 0

super.removeAllViews();

the same without that line... could it be because I placed your code inside the init()?

onFinishInflate()

I suppose that when android starts inflating views it goes from parents to children - and when you are in constructor of custom view - children does not exist yet.

android: how to add children from an xml layout into a custom view - S...

android android-layout android-xml android-custom-view android-resources