Search code examples
javaandroidandroid-viewbinding

How to handle click event in viewbinding


I have a layout with view pager and tabs layout. Viewpager contains two layouts for fragments fragmentpage1 and fragmentpage2. In fragmentpage1.xml i have an imageview who's id is "myimgbtn"

And i have the following code in MainActivity.java :

Private FragmentPage1Binding mfpb;
..
@Override
Protected void oncreate(...){
..
mfpb=FragmentPage1Binding.inflate(getLayoutInflater());
 ImageView myimage=mfpb.myimgbtn;
myimage.setOnclicklistener(v->v.setVisibility(View.Gone););
..

But nothing happens when i click the image,any solutions ?

It works when i use attribute onclick in coresponding xml layout file.


Solution

  • Finally i found the solution. In brief i was calling setContentView on mainlayout and so there is no reference to views contained inside the fragments that it holds. Here's the solution: ViewBinding in Fragment
    But the question is what was myimage referring to?