0

I've been trying to get button's onClickListener working from inflated layout. I was trying this but nothing happens:

LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_profile_fragment, null);
Button svBtn = (Button) view.findViewById(R.id.saveBtn);

svBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        System.out.println("CLICKED");
    }
});

Inside the RecyclerView adapter I inflate the original layout in onCreateViewHolder which has the layout of the cards, and I am able to interact with it:

@Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_card, null);

    return new ItemRowHolder(v);
}

But I would like to interact with the button from a different layout (fragment layout). Is that possible, if so how can I achieve that?

V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
branHazz
  • 39
  • 1
  • 5
  • is it possible to interact with button clicks from different layout? – branHazz Nov 12 '16 at 14:38
  • It looks like it can't register clicks outside of its view `(RecyclerView)`. Because the `my_profile_fragment` inflated layout isn't producing any nullpointers and I can find the button I want to handle clicks of too (which is in `my_profile_fragment` layout). – branHazz Nov 12 '16 at 14:54

2 Answers2

0

try view.getParent() to get your fragment's parent view.

V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
HaroldSer
  • 2,025
  • 2
  • 12
  • 23
  • view.getParent().findViewById - not possible. And if cast it to (View) I get nullpointer View a = (View)view.getParent(); a.findViewById(R.id...... – branHazz Nov 12 '16 at 03:16
0

The way you are doing it, unfortunately is not going to work.

Go to your onBindViewHolder(ViewHolder viewholder, int position) method, and use the fields of the viewholder to directly set your click listener there.

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int position) {
    viewHolder.svBtn.setOnClickListener(this);
}
V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
WillParrish
  • 53
  • 1
  • 4
  • svBtn is completely in different layout not related to this RecyclerView. I tried to inflate the different layout in all RecyclerView methods and set onClickListener there but still doesn't work. – branHazz Nov 12 '16 at 03:11