position of ViewPager item with Data Binding

后端 未结 3 614
广开言路
广开言路 2021-01-13 11:56

I have implemented ViewPager with use of android Data Binding, it is working perfect with data and click events.

I have created interface f

相关标签:
3条回答
  • 2021-01-13 12:28

    Both the answer helped me and both are working, i have found another way also, however its bit lengthy.

    I have taken one more Integer variable in my list_item.xml and setting its value from adapter.

    <data>
        <variable
            name="position"
            type="Integer"/>
    </data>
    

    and passing it in onItemClick

    android:onClick="@{() -> handler.onItemClick(position)}"
    

    then interface will look like this

    public interface ItemClickListener {
        public void onItemClick(int position);
    }
    

    will be setting value of position from instantiateItem()

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        ListItemBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.list_item, container, false);
        binding.setHandler(itemClickListener);
        binding.setPosition(position);
        binding.getRoot().setTag(position);
        container.addView(binding.getRoot());
        return binding.getRoot();
    }
    
    0 讨论(0)
  • 2021-01-13 12:29

    You can pass parameters in the lambda expression, like this:

    android:onClick="@{() -> handler.onItemClick(rootItemView.getTag().toString())}" 
    

    And of course you'll need to edit your interface method and its implementations:

    public void onItemClick(String data);
    
    0 讨论(0)
  • 2021-01-13 12:37

    You can pass view in interface

     public interface ItemClickListener {
         public void onItemClick(View view);
      }
    

    Than set position in tag which you already doing

    binding.getRoot().setTag(position);
    

    And than you can get position from that view param like this

    @Override
    public void onItemClick(View view){
      int position=(int)view.getTag();
    }
    

    For more detail info you can refer http://developers-club.com/posts/267735/

    0 讨论(0)
提交回复
热议问题