How to use Findviewbyid E Onclique in a Fragment?

Asked

Viewed 1,578 times

0

I added two tabs to the main Activity layout, and created two java classes, one for each tab. So I took the buttons of Activity xml from main Activity and put it in the layout of Fragment, but I will use find view by id in the java class of Fragment and it didn’t work.

public class Fragmenta extends Fragment{

    public ImageButton trans ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate( R.layout.fragment_a, container, false );

    trans = (ImageButton)findViewByID(R.id.imagem)

    }
}
  • Instead of this ricycler View I used the image :

1 answer

2

This oncreateview class has to resume a view so to use findviewbyid you have to use the view like this:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragmentlistavideos, container, false);
    mRecyclerView = (RecyclerView) v.findViewById(R.id.mRecicleview);
    return v;
}
  • Ulgor Oliveira I did so

  • Override public View onCreateView(Layoutinflater Inflater, Nullable Viewgroup container, Nullable Bundle savedInstanceState) { View v = Inflater.inflate( R.layout.fragment_a, container, false ); trans = (Imagebutton)findViewById(R.id.trans); Return v; }

  • No, you are returning the inflate and only after you try to use the findviewbyid, you have to pass this inflate to a View and use this view to call the findviewbyid, compare my code with yours

  • all right, just missing you put the v before the findviewbyid, it looks like this: v.findviewbyid

  • Then I would put the buttons and pictures there in the Recycler view Activity ??

  • I’m starting to understand

  • I’ll test it here

  • it worked.. it didn’t turn red , but now one more thing is missing

  • public View onCreateView(Layoutinflater Inflater, Nullable Viewgroup container, Nullable Bundle savedInstanceState) {
 View v = inflater.inflate( R.layout.fragment_a, container, false );
 trans = (ImageButton)v.findViewById(R.id.trans);
 trans.setOnClickListener( new View.OnClickListener() {
 @Override
 public void onClick(View v) {&#xTo; startActivity( new Intent( Fragmenta.this, Cronogramaactivity.class ) ); } } ); Return v; } }

  • startActivity turned red as if it could not use

  • reycleview was just example, to use the startactivity vc tb has to put the v before is like this: v.startactivity

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.