在scrollview中将一个片段切换到另一个片段

时间:2018-08-24 10:48:55

标签: android

我有一个滚动视图,里面有一个片段,当我单击一个按钮时,我想将片段切换到另一个片段。 我尝试了片段交易,但出现此错误

  

java.lang.IllegalStateException:ScrollView只能托管一个直接子级

代码:

Search search = new Search();
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.scrollView,search).commit();

1 个答案:

答案 0 :(得分:1)

您必须使用FrameLayout作为ScrollView的子级,然后使用事务来更改片段

xml( partial ):

import PhotoSwipe from 'photoswipe';
import PhotoSwipeUI_Default from 'photoswipe/dist/photoswipe-ui-default';

const lang = document.documentElement.lang || 'en';
const shareOptions = {
  en: [{
      id: 'facebook',
      label: 'Share on Facebook',
      url: 'https://www.facebook.com/sharer/sharer.php?u={{url}}'
    },
    {
      id: 'twitter',
      label: 'Tweet',
      url: 'https://twitter.com/intent/tweet?text={{text}}&url={{url}}'
    },
    {
      id: 'pinterest',
      label: 'Pin it',
      url: 'http://www.pinterest.com/pin/create/button/?url={{url}}&media={{image_url}}&description={{text}}'
    },
    {
      id: 'download',
      label: 'Download image',
      url: '{{raw_image_url}}',
      download: true
    }
  ],
  de: [{
      id: 'facebook',
      label: 'Auf Facebook teilen',
      url: 'https://www.facebook.com/sharer/sharer.php?u={{url}}'
    },
    {
      id: 'twitter',
      label: 'Tweet',
      url: 'https://twitter.com/intent/tweet?text={{text}}&url={{url}}'
    },
    {
      id: 'pinterest',
      label: 'Pin it',
      url: 'http://www.pinterest.com/pin/create/button/?url={{url}}&media={{image_url}}&description={{text}}'
    },
    {
      id: 'download',
      label: 'Bild herunterladen',
      url: '{{raw_image_url}}',
      download: true
    }
  ]
};

export default function (selector, addCaption = false) {
  // parse slide data (url, title, size ...) from DOM elements
  // (children of selector)
  const parseThumbnailElements = function (el, addCaption) {
    var thumbElements = el.querySelectorAll('figure'),
      numNodes = thumbElements.length,
      items = [],
      figureEl,
      linkEl,
      size,
      item;

    for (let i = 0; i < numNodes; i++) {

      figureEl = thumbElements[i]; // <figure> element

      // include only element nodes
      if (figureEl.nodeType !== 1) {
        continue;
      }

      linkEl = figureEl.children[0]; // <a> element

      const retina = linkEl.getAttribute('data-retina');

      if (retina !== null && !!retina === true) {
        item = JSON.parse(linkEl.getAttribute('data-size'));
      } else {
        size = linkEl.getAttribute('data-size').split('x');
        // create slide object
        item = {
          src: linkEl.getAttribute('href'),
          w: parseInt(size[0], 10),
          h: parseInt(size[1], 10)
        };
      }


      if (figureEl.children.length > 1 && addCaption) {
        // <figcaption> content
        item.title = figureEl.children[1].innerHTML;
      }

      if (linkEl.children.length > 0) {
        // <img> thumbnail element, retrieving thumbnail urls
        item.msrc = linkEl.children[0].getAttribute('src');
      }

      item.el = figureEl; // save link to element for getThumbBoundsFn
      items.push(item);
    }

    return items;
  };


  // find nearest parent element
  const closest = function closest(el, fn) {
    return el && (fn(el) ? el : closest(el.parentNode, fn));
  };

  // triggers when user clicks on thumbnail
  const onThumbnailsClick = function (e) {
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : e.returnValue = false;

    const eTarget = e.target || e.srcElement;

    // if ($(eTarget).parents('.is-dragging').length) {
    //     return;
    // }

    // find root element of slide
    const clickedListItem = closest(eTarget, (el) => {
      return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
    });

    if (!clickedListItem) {
      return;
    }

    // find index of clicked item by looping through all child nodes
    // alternatively, you may define index via data- attribute
    var clickedGallery = clickedListItem.parentNode,
      childNodes = clickedListItem.parentNode.childNodes,
      numChildNodes = childNodes.length,
      nodeIndex = 0,
      index;

    for (let i = 0; i < numChildNodes; i++) {
      if (childNodes[i].nodeType !== 1) {
        continue;
      }

      if (childNodes[i] === clickedListItem) {
        index = nodeIndex;
        break;
      }
      nodeIndex++;
    }

    if (index >= 0) {
      // open PhotoSwipe if valid index found
      openPhotoSwipe(index, clickedGallery);
    }
    return false;
  };

  // parse picture index and gallery index from URL (#&pid=1&gid=2)
  const photoswipeParseHash = function () {
    const hash = window.location.hash.substring(1),
      params = {};

    if (hash.length < 5) {
      return params;
    }

    const vars = hash.split('&');
    for (let i = 0; i < vars.length; i++) {
      if (!vars[i]) {
        continue;
      }
      const pair = vars[i].split('=');
      if (pair.length < 2) {
        continue;
      }
      params[pair[0]] = pair[1];
    }

    if (params.gid) {
      params.gid = parseInt(params.gid, 10);
    }

    return params;
  };

  const openPhotoSwipe = function (index, galleryElement, disableAnimation, fromURL) {
    var pswpElement = document.querySelectorAll('.pswp')[0],
      gallery,
      options,
      items;

    items = parseThumbnailElements(galleryElement, addCaption);

    // define options (if needed)
    options = {
      shareButtons: shareOptions[lang],
      // define gallery index (for URL)
      galleryUID: galleryElement.getAttribute('data-pswp-uid'),
      allowPanToNext: true,
      tapToClose: true,
      getImageURLForShare: function () {
        return gallery.currItem.src || '';
      },
      getThumbBoundsFn: function (index) {
        // See Options -> getThumbBoundsFn section of documentation for more info
        var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
          pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
          rect = thumbnail.getBoundingClientRect();

        return {
          x: rect.left,
          y: rect.top + pageYScroll,
          w: rect.width
        };
      }

    };

    // PhotoSwipe opened from URL
    if (fromURL) {
      if (options.galleryPIDs) {
        // parse real index when custom PIDs are used
        // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
        for (let i = 0; i < items.length; i++) {
          if (items[i].pid == index) {
            options.index = i;
            break;
          }
        }
      } else {
        // in URL indexes start from 1
        options.index = parseInt(index, 10) - 1;
      }
    } else {
      options.index = parseInt(index, 10);
    }

    // exit if index not found
    if (isNaN(options.index)) {
      return;
    }

    if (disableAnimation) {
      options.showAnimationDuration = 0;
    }

    // Pass data to PhotoSwipe and initialize it
    gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);


    // create variable that will store real size of viewport
    let useLargeImages = false;
    let firstResize = true;
    let realViewportWidth;
    let imageSrcWillChange;

    // beforeResize event fires each time size of gallery viewport updates
    gallery.listen('beforeResize', function () {
      // gallery.viewportSize.x - width of PhotoSwipe viewport
      // gallery.viewportSize.y - height of PhotoSwipe viewport
      // window.devicePixelRatio - ratio between physical pixels and device independent pixels (Number)

      // calculate real pixels when size changes
      realViewportWidth = gallery.viewportSize.x * window.devicePixelRatio;

      // Code below is needed if you want image to switch dynamically on window.resize

      // Find out if current images need to be changed
      if (useLargeImages && realViewportWidth <= 1024) {
        useLargeImages = false;
        imageSrcWillChange = true;
      } else if (!useLargeImages && realViewportWidth > 1024) {
        useLargeImages = true;
        imageSrcWillChange = true;
      }

      // Invalidate items only when source is changed and when it's not the first update
      if (imageSrcWillChange && !firstResize) {
        // invalidateCurrItems sets a flag on slides that are in DOM,
        // which will force update of content (image) on window.resize.
        gallery.invalidateCurrItems();
      }

      if (firstResize) {
        firstResize = false;
      }

      imageSrcWillChange = false;

    });


    // gettingData event fires each time PhotoSwipe retrieves image source & size
    gallery.listen('gettingData', function (index, item) {
      let pixelRatio = window.devicePixelRatio;
      let windowWidth = window.innerWidth;
      // Set image source & size based on viewport width
      if ('mobile' in item) {
        // below tablet size
        if (windowWidth <= 991) {
          if (pixelRatio > 1) {
            item.src = item.mobile.retina.src;
            item.w = item.mobile.retina.w;
            item.h = item.mobile.retina.h;
          } else {
            item.src = item.mobile.default.src;
            item.w = item.mobile.default.w;
            item.h = item.mobile.default.h;
          }
        } else {
          if (pixelRatio > 1 || windowWidth > 1900) {
            item.src = item.desktop.retina.src;
            item.w = item.desktop.retina.w;
            item.h = item.desktop.retina.h;
          } else {
            item.src = item.desktop.default.src;
            item.w = item.desktop.default.w;
            item.h = item.desktop.default.h;
          }
        }
      }
    });

    gallery.init();
  };

  // loop through all gallery elements and bind events
  const galleryElements = document.querySelectorAll(selector);

  for (let i = 0, l = galleryElements.length; i < l; i++) {
    galleryElements[i].setAttribute('data-pswp-uid', i + 1);
    galleryElements[i].onclick = onThumbnailsClick;
  }

  // Parse URL and open gallery if it contains #&pid=3&gid=1
  const hashData = photoswipeParseHash();
  if (hashData.pid && hashData.gid) {
    openPhotoSwipe(hashData.pid, galleryElements[hashData.gid - 1], true, true);
  }
}

然后使用Java

<ScrollView>
   <FrameLayout
    android:id="@+id/frameLayout"/>
</ScrollView>