Search code examples
androidtabristabris-js

Adding Multiple TextView's to CollectionView in Tabrisjs


I'm able to easily add Widgets to CollectionView, but I can't seem to add more than one Widget type. I'm trying to add 2 TextView's. Here's what I got so far, it only outputs the firstName twice. (this runs in Playground)

Also, is it possible to add events to each TextView? like: .on('tap', () => {

I do see how the .on('select',works, on the Collection View, but I want to add event to each individual TextView's

Thanks.

Screenshot showing no last name

// Create a collection view, initialize its cells and fill it with items
const {CollectionView, Composite, ImageView, TextView, ui} = require('tabris');

let people = [
  ['Bob', 'Smith',],
  ['Fred', 'Jones'],
  ['James', 'Mackay'],
].map(([firstName, lastName]) => ({firstName, lastName}));

new CollectionView({
  left: 0, top: 0, right: 0, bottom: 0,
  itemCount: people.length,
  cellHeight: 56,

  createCell: () => {
    let cell = new Composite();

    new TextView({
      left: 30, top: 10,
      alignment: 'left'
    })
    .appendTo(cell);

    let txvLastName = new TextView({
      left: 50, top: 25,
      alignment: 'right'
    })
    .appendTo(cell);
    return cell;
  },
  updateCell: (cell, index) => {
    let person = people[index];
    cell.apply({
      TextView: {text: person.firstName},
      txvLastName: {text: person.lastName},
    });
  }
}).on('select', ({index}) => console.log('selected', people[index].firstName))
  .appendTo(ui.contentView);

Solution

  • The apply method takes a Widget selector, which works similarly to CSS selectors and are documented at the aforementioned link. You are referencing a JavaScript variable, which is not supported and not in scope in the updateCell callback function.

    I would update your createCell callback so that each of the elements has a distinct class on them and reference that in your updateCell callback:

    createCell: () => {
      let cell = new Composite();
    
      new TextView({
        left: 30, top: 10,
        class: 'firstName',
        alignment: 'left'
      }).appendTo(cell);
    
      new TextView({
        left: 50, top: 25,
        class: 'lastName',
        alignment: 'right'
      }).appendTo(cell);
      return cell;
    },
    updateCell: (cell, index) => {
      let person = people[index];
      cell.apply({
        '.firstName': {text: person.firstName},
        '.lastName': {text: person.lastName},
      });
    }