Last active
September 30, 2022 15:02
-
-
Save ioxua/9b0d8a45e39fcb52695ce83284c122ca to your computer and use it in GitHub Desktop.
Simple implementation of callback on Android Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Activity extends AppCompatActivity implements MyAdapter.Callback { | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.my_layout); | |
RecyclerView recycler = findViewById(R.id.recycler_view); | |
recycler.setAdapter(new MyAdapter(this)); | |
} | |
@Override | |
public void onChangePosition(int position) { | |
// Here you have access to almost everything from inside your Adapter AND your Activity :D | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyAdapter extends RecyclerView.Adapter<CustomViewHolder> { | |
public interface Callback { | |
void onChangePosition(int position); | |
} | |
private MyAdapter.Callback mCallback; | |
public MyAdapter(MyAdapter.Callback callback) { | |
this.mCallback = callback; | |
} | |
public void setCallback(MyAdapter.Callback callback) { | |
this.mCallback = callback; | |
} | |
@Override | |
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { | |
View v = LayoutInflater.from(parent.getContext()) | |
.inflate(R.layout.my_view, parent, false); | |
return new CustomViewHolder(v); | |
} | |
@Override | |
public void onBindViewHolder(ViewHolder holder, int position) { | |
this.mCallback.onChangePosition(position); | |
} | |
class CustomViewHolder extends RecyclerView.ViewHolder { | |
CustomViewHolder(View view) { | |
super(view); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment