logo
down
shadow

android listview row with variable number of child views


android listview row with variable number of child views

By : Rijo Panakkal
Date : November 22 2020, 10:48 AM
wish helps you I have a ListView and each row show a number of TextViews. Some rows contain 1 TextView, while others can contain any number of TextViews, each placed below the previous. , you can create TextView or inflate custom layout from the code
code :


Share : facebook icon twitter icon
Android: Access child views from a ListView

Android: Access child views from a ListView


By : user412126
Date : March 29 2020, 07:55 AM
Any of those help See: Android ListView: get data index of visible item and combine with part of Feet's answer above, can give you something like:
code :
int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
  Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
  return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);
In an android ListView, how can I iterate/manipulate all the child views, not just the visible ones?

In an android ListView, how can I iterate/manipulate all the child views, not just the visible ones?


By : user1704434
Date : March 29 2020, 07:55 AM
may help you . List13 from the API Demos does something similar using OnScrollStateChanged. There may be a better way, though:
code :
public void onScrollStateChanged(AbsListView view, int scrollState) {
    switch (scrollState) {
    case OnScrollListener.SCROLL_STATE_IDLE:
        mBusy = false;

        int first = view.getFirstVisiblePosition();
        int count = view.getChildCount();
        for (int i=0; i<count; i++) {
            TextView t = (TextView)view.getChildAt(i);
            if (t.getTag() != null) {
                t.setText(mStrings[first + i]);
                t.setTag(null);
            }
        }

        mStatus.setText("Idle");
        break;
public void onScroll(AbsListView v, int firstVisibleItem, int visibleCount, int totalItemCount)
{
    ListView lv = this.getListView();
    int childCount = lv.getChildCount();

    for (int i = 0; i < childCount; i++)
    {
        View v = lv.getChildAt(i);
        TextView tx = (TextView) v.findViewById(R.id.mytext);
        tx.setTextSize(textSize);
    }
}
Fit variable number of views on screen in android

Fit variable number of views on screen in android


By : DaveS
Date : March 29 2020, 07:55 AM
To fix the issue you can do Hm, if you will draw the images yourself at absolute positions within some view of size totalSize (width/height for horizontal/vertical), this class will calculate the first position (left/top for horizontal/vertical).
You have to give it the target area size + list of the image sizes in the desired orientation (it's written in generic way, so you can use it both horizontally or vertically).
code :
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ImagePositioning {

    /**
     * Return possible positions for various images from the list, to fit into {@code totalSize}.
     * <p>
     * When overlapping is needed, image 0 is at bottom, and last image is reaching beyond {@code
     * totalSize} (should be cut by view draw), each next image overlapping the previous one.
     * <p>
     * When there's enough space for every image even with spare room, images are centered into
     * available spare space.
     *
     * @param totalSize
     *         Total size of available space (width for horizontal or height for vertical)
     * @param imageSizes
     *         Widths (or heights) of images to position.
     * @return List with starting position for images.
     */
    public static List<Integer> calculatePositions(
            final int totalSize, final List<Integer> imageSizes) {
        if (null == imageSizes || imageSizes.isEmpty()) return Collections.emptyList();
        final int imagesN = imageSizes.size();
        int imagesTotalSize = 0;
        for (int i = 0; i < imagesN; ++i) imagesTotalSize += imageSizes.get(i);
        double freeSpace = totalSize - imagesTotalSize, posX = 0.0;
        freeSpace /= imagesN;        // free space per image (unweighted)
        if (0 < freeSpace) posX = 0.5 * freeSpace;
        final List<Integer> r = new ArrayList<>(imagesN);
        for (int i = 0; i < imagesN; ++i) {
            r.add((int)posX);
            posX += freeSpace + imageSizes.get(i);
        }
        return r;
    }

    /**
     * Return possible positions for various images from the list, to fit into {@code totalSize}.
     * <p>
     * When overlapping is needed, image 0 is at bottom, and last image is reaching beyond {@code
     * totalSize} (should be cut by view draw), each next image overlapping the previous one.
     * <p>
     * When there's enough space for every image even with spare room, images are centered into
     * available spare space.
     * <p>
     * This method is different from {@link #calculatePositions(int, List)} by weighing the
     * spare/cut space per image by its own size, so larger images will get cut more than smaller
     * images.
     *
     * @param totalSize
     *         Total size of available space (width for horizontal or height for vertical)
     * @param imageSizes
     *         Widths (or heights) of images to position.
     * @return List with starting position for images.
     */
    public static List<Integer> calculateWeightedPositions(
            final int totalSize, final List<Integer> imageSizes) {
        if (null == imageSizes || imageSizes.isEmpty()) return Collections.emptyList();
        final int imagesN = imageSizes.size();
        int imagesTotalSize = 0;
        for (int i = 0; i < imagesN; ++i) imagesTotalSize += imageSizes.get(i);
        double freeSpace = totalSize - imagesTotalSize, posX = 0.0, totalInv = 1.0 / imagesTotalSize;
        final List<Integer> r = new ArrayList<>(imagesN);
        for (int i = 0; i < imagesN; ++i) {
            final Integer imageSize = imageSizes.get(i);
            // calculate weighted free space for this particular image
            double freeSpaceWeighted = freeSpace * imageSize * totalInv;
            if (0 < freeSpaceWeighted) r.add((int)(posX + 0.5 * freeSpaceWeighted));
            else r.add((int)posX);
            posX += freeSpaceWeighted + imageSize;
        }
        return r;
    }
}
import junit.framework.Assert;

import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ImagePositioningTest {

    ///////////////////////////////////////////////////////////////////////////
    // Fixed per-image positioning
    ///////////////////////////////////////////////////////////////////////////

    @Test
    public void nullList() throws Exception {
        final List<Integer> r = ImagePositioning.calculatePositions(0, null);
        Assert.assertNotNull(r);
        Assert.assertTrue(r.isEmpty());
    }

    @Test
    public void emptyList() throws Exception {
        List<Integer> list = Collections.emptyList();
        final List<Integer> r = ImagePositioning.calculatePositions(0, list);
        Assert.assertNotNull(r);
        Assert.assertTrue(r.isEmpty());
    }

    @Test
    public void singleImageFullWidth() throws Exception {
        List<Integer> list = Arrays.asList(500);
        final List<Integer> r = ImagePositioning.calculatePositions(500, list);
        Assert.assertNotNull(r);
        Assert.assertEquals(0, r.get(0).intValue());
    }

    @Test
    public void singleImageSmallerWidth() throws Exception {
        List<Integer> list = Arrays.asList(500);
        final List<Integer> r = ImagePositioning.calculatePositions(1000, list);
        Assert.assertNotNull(r);
        Assert.assertEquals(250, r.get(0).intValue());
    }

    @Test
    public void simpleWidths() throws Exception {
        List<Integer> listTwo = Arrays.asList(200, 200), r;

        r = ImagePositioning.calculatePositions(300, listTwo);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(0, 150), r);

        r = ImagePositioning.calculatePositions(500, listTwo);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(25, 275), r);

        List<Integer> listThree = Arrays.asList(100, 200, 100);

        r = ImagePositioning.calculatePositions(310, listThree);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(0, 70, 240), r);

        r = ImagePositioning.calculatePositions(400, listThree);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(0, 100, 300), r);

        r = ImagePositioning.calculatePositions(490, listThree);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(15, 145, 375), r);
    }

    ///////////////////////////////////////////////////////////////////////////
    // Weighted positioning
    ///////////////////////////////////////////////////////////////////////////

    @Test
    public void wNullList() throws Exception {
        final List<Integer> r = ImagePositioning.calculateWeightedPositions(0, null);
        Assert.assertNotNull(r);
        Assert.assertTrue(r.isEmpty());
    }

    @Test
    public void wEmptyList() throws Exception {
        List<Integer> list = Collections.emptyList();
        final List<Integer> r = ImagePositioning.calculateWeightedPositions(0, list);
        Assert.assertNotNull(r);
        Assert.assertTrue(r.isEmpty());
    }

    @Test
    public void wSingleImageFullWidth() throws Exception {
        List<Integer> list = Arrays.asList(500);
        final List<Integer> r = ImagePositioning.calculateWeightedPositions(500, list);
        Assert.assertNotNull(r);
        Assert.assertEquals(0, r.get(0).intValue());
    }

    @Test
    public void wSingleImageSmallerWidth() throws Exception {
        List<Integer> list = Arrays.asList(500);
        final List<Integer> r = ImagePositioning.calculateWeightedPositions(1000, list);
        Assert.assertNotNull(r);
        Assert.assertEquals(250, r.get(0).intValue());
    }

    @Test
    public void wSimpleWidths() throws Exception {
        List<Integer> listTwo = Arrays.asList(200, 200), r;

        r = ImagePositioning.calculateWeightedPositions(300, listTwo);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(0, 150), r);

        r = ImagePositioning.calculateWeightedPositions(500, listTwo);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(25, 275), r);

        List<Integer> listThree = Arrays.asList(100, 200, 100);

        r = ImagePositioning.calculateWeightedPositions(310, listThree);
        Assert.assertNotNull(r);
        Assert.assertEquals(0, r.get(0), 2.0);
        Assert.assertEquals(310.0/400*100, r.get(1), 2.0);
        Assert.assertEquals(310.0/400*100 + 310.0/400*200, r.get(2), 2.0);

        r = ImagePositioning.calculateWeightedPositions(400, listThree);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(0, 100, 300), r);

        r = ImagePositioning.calculateWeightedPositions(490, listThree);
        Assert.assertNotNull(r);
        Assert.assertEquals(Arrays.asList(11, 145, 378), r);
    }
}
Android when looping through LinearLayout child views it always gives me that child views are the same

Android when looping through LinearLayout child views it always gives me that child views are the same


By : Cappy McContent
Date : March 29 2020, 07:55 AM
will be helpful for those in need Start with a condition for EditText. EditText is subclass of TextView, so "instanceof TextView" returns true for its instances.
code :
if (linearLayout.getChildAt(i) instanceof EditText){
    EditText editText = (EditText) linearLayout.getChildAt(i);
    editText.setText("EditText " + i);
} else if (linearLayout.getChildAt(i) instanceof TextView){
     TextView someTetView = (TextView) linearLayout.getChildAt(i);
     someTetView.setText("TV " + i);
}else {
   //do nothing
}
Android Espresso : Saving number of rows in listview to variable

Android Espresso : Saving number of rows in listview to variable


By : tekitisy
Date : March 29 2020, 07:55 AM
will be helpful for those in need You can assert the number of element in your RecyclerListView or ListView by using a custom Matcher like this :
code :
/**
 * Test if a RecyclerView contain the right amount of elements
 */
fun withListSize(size: Int): Matcher<View> {
    return object : TypeSafeMatcher<View>() {
        var listSize = 0
        public override fun matchesSafely(view: View): Boolean {
            if ((view !is RecyclerView)) throw IllegalStateException("You cannot assert withListSize in none RecyclerView View")
            listSize = view.adapter.itemCount
            return listSize == size
        }

        override fun describeTo(description: Description) {
            description.appendText("ListView should have $size items and currently $listSize items")
        }
    }
}
         var listSize = 0
    Espresso.onView(ViewMatchers.withId(R.id.list))
            .check(ViewAssertions.matches(object : TypeSafeMatcher<View>() {
                public override fun matchesSafely(view: View): Boolean {
                    if ((view !is RecyclerView)) throw IllegalStateException("You cannot assert withListSize in none RecyclerView View")
                    listSize = view.adapter.itemCount
                    return listSize !=0
                }

                override fun describeTo(description: Description) {
                    description.appendText("ListView should not be empty")
                }
            }))

    // ADD TO the list

    Espresso.onView(ViewMatchers.withId(R.id.list))
            .check(ViewAssertions.matches(Matchers.allOf(withListSize(listSize + 1), ViewMatchers.isDisplayed())))
Related Posts Related Posts :
  • Android Studio gradle build failed for hello world app
  • Slide a layout up from bottom of screen
  • Play HTML5 video in iOS/Android native media player
  • How to rescale a bitmap file in android?
  • No view found for id 0x for fragment after rotation?
  • Define different themable styles to the same widget types
  • ProGuard not working in my app
  • FragmentTransaction from BaseAdapter
  • Connecting multiple devices in a Wifi Direct group
  • Why TabActivity is deprecated in android
  • How to capture low resolution picture using android camera
  • android preferenceactivity padding in landscape orientation
  • How can I store cookie in webview?
  • Passing variables from one activity to another
  • Create Multicolored Pie Chart in Android Studio
  • how to kill progress dialog in android
  • Show Error on the tip of the Edit Text Android
  • How do I use getWindowManager() by another java file
  • fetching images from gallery on android phones with internal storage
  • How to discover devices like Google TV and Nexus-Q using MediaRoute API on Android?
  • "Unfortunately your app stopped working"- Facebook Integration for Android
  • How to animate button in android?
  • Resource Not Found Exception in class without context or activity
  • Launching Android Netflix App And Passing Video Id
  • Making a Phone Call with a Number Extension
  • NullPointerException at BoringLayout.isBoring is anything but boring
  • java.lang.RuntimeException: Unable to get provider
  • Testing custom Views with Robolectric
  • tools:listheader doesn't work although tools:listitem does
  • oppo, vivo app kill notification not coming in android fcm
  • OnClick Method could not function correctly with if else statement
  • Best method to download image from url in Android
  • How can I open Drawer Layout moving all the view and not just slide over?
  • how to show profile pictures of friends in a list view?
  • Creating TimePickerDialog with custom style in Android
  • Android 2.3.6 support library v7 option menu is missing
  • need of vblank in Display subssytem
  • Android MP4 stream - Video cannot be played
  • FastAdapter: Undo button does not show up after swipe
  • What are reasons to pass getActivity as the LifecycleOwner to the LiveData's observe method in a fragment?
  • Implement Face Recognition in Android
  • Titanium studio cannot run "titanium" command in terminal
  • How to execute command line ffmpeg commands programatically in android?
  • Make Android List Items clickable with each item pointing to a different link
  • listview runs successfully, but nothing is display in emulator
  • How to zoom in a bitmap with high resolution?
  • Passing listView data through intent
  • Google map route direction show by arrows in android v2
  • how to start "uiautomator test run" from android code?
  • Proguard in Android Library
  • Alarm Clock from GIT - Gives error - Android
  • Mock injection using Mockito - Android
  • Get Bitmap from universal image loader
  • Unable to include custom font in android
  • Basics on using logcat in Android development
  • Android: Clear cache programmatically
  • Android: pass object without serialization
  • Can not scroll and click item on gridview inside scrollview
  • Android device keeps disconnecting from adb / eclipse
  • Volley cannot create cache directory. Could not clean up file
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org