I'm using only one SwitchCompat in my RecyclerView adapter. I need position of the clicked item on RecyclerView and it's working fine when I use TextView instead of SwitchCompat. But SwitchCompat have no response and no position returned.
Can anyone help me please? Here's the Adapter file.
public class Setting_Recycler_Adapter extends RecyclerView.Adapter<Setting_Recycler_Adapter.ViewHolder> {
private static final String TAG = "val" ;
private Context mContext;
private ArrayList<Channel_Model> channelsData;
private Setting_Recycler_Adapter.ClickInterface click;
public Setting_Recycler_Adapter(Context mContext, ArrayList<Channel_Model> data,Setting_Recycler_Adapter.ClickInterface clik) {
this.mContext = mContext;
this.channelsData = data;
this.click = clik;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
SwitchCompat mSwitchCompat;
public ViewHolder(View itemView) {
super(itemView);
mSwitchCompat = (SwitchCompat) itemView.findViewById(R.id.setting_channel_switch);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
click.posClicked((short)getAdapterPosition());
}
}
#Override
public Setting_Recycler_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.setting_recycler, parent, false);
return new Setting_Recycler_Adapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final Setting_Recycler_Adapter.ViewHolder holder, int position) {
holder.mSwitchCompat.setText(channelsData.get(position).getTitle());
holder.mSwitchCompat.setChecked(channelsData.get(position).isChannel());
}
#Override
public int getItemCount() {
return channelsData.size();
}
interface ClickInterface{void posClicked(short p);
}
And the RecyclerView layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="rtl"
android:textDirection="rtl">
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/setting_channel_switch"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="channel Name"
android:textSize="17sp"/>
</LinearLayout>
You need to set the onSetCheckedChangeListener along with onTouchListener for your SwitchCompat. So the implementation inside your ViewHolder class should look like the following.
public class ViewHolder extends RecyclerView.ViewHolder {
SwitchCompat mSwitchCompat;
Boolean isTouched = false;
public ViewHolder(View itemView) {
super(itemView);
mSwitchCompat = (SwitchCompat) itemView.findViewById(R.id.setting_channel_switch);
mSwitchCompat.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
isTouched = true;
return false;
}
});
mSwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isTouched) {
isTouched = false;
if (isChecked) {
click.posClicked((short)getAdapterPosition());
} else {
// Do something on un-checking the SwitchCompat
}
}
}
});
}
}
Hope that helps!
Related
I'm making a feature that pops up an empty dialog and enters comments.
The dialog consists of a RecyclerView.
And items consist of EditText.
Only one line of comments can be entered.
Pressing EnterKey dynamically creates the next comment input field.
However, when i press the enter key, two items are created.
Using the Toast message, I noticed that OnAddComment() was called twice.
Even after debugging, I am not sure why there are two.
What's the problem?
writing_comment_item.xml
<EditText
android:id="#+id/comment_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center_vertical"
android:drawableLeft="#drawable/ic_bullet_point"
android:drawablePadding="5dp"
android:layout_marginHorizontal="10dp"
android:background="#null"
android:textSize="15sp"
android:inputType="text"
android:maxLines="1"
android:maxLength="22"
android:imeOptions="actionNone"/>
WritingCommentDialogFragment.java
public class WritingCommentDialogFragment extends DialogFragment {
List<String> items;
WritingCommentAdapter commentAdapter;
RecyclerView comment_rv;
LinearLayoutManager layoutManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_writing_comment_dialog, container, false);
initViews(view);
prepareForRecyclerView();
commentAdapter.setOnWrtingCommentListener(new WritingCommentAdapter.OnWritingCommentListener() {
#Override
public void OnAddComment(int pos) {
items.add("TEST");
commentAdapter.addItems(items, pos);
}
});
return view;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
#Override
public void onResume() {
super.onResume();
setDialogSize();
}
private void setDialogSize() {
getDialog().getWindow().setLayout(1000, 1000);
}
private void initViews(View view) {
comment_rv = view.findViewById(R.id.comment_rv);
}
private void prepareForRecyclerView() {
commentAdapter = new WritingCommentAdapter();
layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, true);
comment_rv.setLayoutManager(layoutManager);
comment_rv.setAdapter(commentAdapter);
items = new ArrayList<>();
items.add(null);
commentAdapter.addItem(items);
}
}
Adapter.java
public class WritingCommentAdapter extends RecyclerView.Adapter<WritingCommentAdapter.ViewHolder> {
List<String> commentItems;
OnWritingCommentListener listener;
Context context;
public void setOnWrtingCommentListener(OnWritingCommentListener listener) {
this.listener = listener;
}
public void addItem(List<String> items) {
commentItems = items;
}
public void addItems(List<String> items, int pos) {
commentItems = items;
notifyItemInserted(pos);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.writing_comment_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return commentItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
EditText comment;
public ViewHolder(#NonNull View itemView) {
super(itemView);
comment = itemView.findViewById(R.id.comment_edit);
comment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override // IME Option NONE ( ENTER KEY)
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(listener != null) {
listener.OnAddComment(getAdapterPosition());
}
return true;
}
});
}
public void setItem(String str) {
comment.setText(str);
}
}
public interface OnWritingCommentListener {
public void OnAddComment(int pos);
}
}
It is receiving callback 2 times. One for action ACTION_DOWN & one for action ACTION_UP when he is pressing the enter button.
if(listener != null) { if( event.getAction() == KeyEvent.ACTION_DOWN) { listener.OnAddComment(getAdapterPosition()); } }
So add comments only when action is ACTION_DOWN.
I have multiple options for a poll and user can select only one option. i am getting options in recycler view with a checkbox and textview.
i want to uncheck previous selected checkbox if user select another checkbox and get selected text by pressing submit button.
here is my recycler view code.
public class Poll_Options_recyclerView_Adapter extends RecyclerView.Adapter<Poll_Options_recyclerView_Adapter.MyViewHolder> {
public List<Poll_Option_Result> result = new ArrayList<>();
Context mycontext;
public Poll_Options_recyclerView_Adapter(List<Poll_Option_Result> result, Context context) {
this.result = result;
this.mycontext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_option_rec_list, parent, false);
return new MyViewHolder(itemView, mycontext, result);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView poll_option;
CheckBox checkBox;
List<Poll_Option_Result> result_List = new ArrayList<>();
Context mycontext;
public MyViewHolder(View itemView, Context mycontext, List<Poll_Option_Result> result_List) {
super(itemView);
this.result_List = result_List;
this.mycontext = mycontext;
poll_option = (TextView) itemView.findViewById(R.id.optionA);
checkBox=(CheckBox)itemView.findViewById(R.id.check_box);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
#Override
public void onBindViewHolder(Poll_Options_recyclerView_Adapter.MyViewHolder holder, int position) {
final Poll_Option_Result ResultList = result.get(position);
holder.poll_option.setText(ResultList.getOption());
}
#Override
public int getItemCount() {
return result.size();
}
}
and here is my recycler view custom xml code.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5"
>
<CheckBox
android:id="#+id/check_box"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_weight="4.5"
android:layout_height="wrap_content"
android:text="xyz"
android:layout_marginLeft="20dp"
android:textColor="#color/colortoolbartitle"
android:padding="5dp"
android:id="#+id/optionA"/>
private int mCheckedPostion = -1;// no selection by default
Done by adding this code in onBindViewHolder
#Override
public void onBindViewHolder(final Poll_Options_recyclerView_Adapter.MyViewHolder holder, final int position) {
final Poll_Option_Result ResultList = result.get(position);
holder.poll_option.setText(ResultList.getOption());
//check checkbox and uncheck previous selected button
holder.checkBox.setChecked(position == mCheckedPostion);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == mCheckedPostion) {
holder.checkBox.setChecked(false);
StringGen.username = "";
mCheckedPostion = -1;
} else {
mCheckedPostion = position;
StringGen.username = holder.poll_option.getText().toString();
Toast.makeText(mycontext, "select : "+position+holder.poll_option.getText(), Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
}
});
}
I want to add, for each row in ListView, a checkbox which will be activated and shown on long press, I don't know whether I think correctly, I should add in row layout a Checkbox which is default hidden and when action start all check box on list will be shown and able to check?
To show CheckBox on each row:
1. Add an extra boolean variable isLongPressed to your adapter class and initialized with default false value from adapter constructor.
2. In your adapter getView()/ onBindViewHolder() method add an condition like this:
CheckBox checkBox = (CheckBox) view.findViewById(R.id.check);
if(isLongPressed)
{
checkBox.setVisibility(View.VISIBLE);
} else {
checkBox.setVisibility(View.GONE);
}
3. Add an method showCheckbox() to your adapter class to update ListView with checkbox visible state.
public void showCheckbox()
{
isLongPressed = true;
notifyDataSetChanged(); // Required for update
}
4. Call showCheckbox() from onItemLongClick:
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Long Click", Toast.LENGTH_SHORT).show();
your_adapter.showCheckbox();
return true;
}
});
Here is good tutorial about Contextual Action Mode
Hope this will help~
Try this:
We will use a recyclerview, and a checkbox adapter
Chechbox Adapter layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/checkbox_adapter_item_height"
android:gravity="center_vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal">
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:theme="#style/MyCheckBoxTheme"
android:clickable="false"
android:longClickable="false"
android:focusable="false"/>
<TextView
android:id="#+id/tvItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item1"
android:visibility="visible"
android:padding="6dp"
android:paddingStart="12dp"
android:textColor="#color/colorMaterialBlack"
android:textSize="16sp" />
</LinearLayout>
A style for checkbox, keep this in style
<style name="MyCheckBoxTheme" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">#color/colorBlackDimText</item>
<item name="colorControlActivated">#color/greenStatus</item>
</style>
A Model for the Checkbox adapter you can define/add/remove vars in your model
public class CheckboxTitlesData {
private String title;
private boolean isSelected;
public CheckboxTitlesData(String title, boolean isSelected) {
this.title = title;
this.isSelected = isSelected;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
Checkbox Adapter
public class CheckboxTitleAdapter extends RecyclerView.Adapter<CheckboxTitleAdapter.ViewHolder> implements GenericAdapterInterface{
List<CheckboxTitlesData> dataList = new ArrayList<>();
private CheckboxTitlesData previousSelection;
protected MyApplication.MenuSelectionListener listener;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(getRootLayout(), parent, false);
return new ViewHolder(view);
}
public CheckboxTitleAdapter(MyApplication.MenuSelectionListener listener){
this.listener = listener;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
CheckboxTitlesData data = dataList.get(position);
if (data.isSelected()){
previousSelection = data;
holder.checkBox.setChecked(true);
}else holder.checkBox.setChecked(false);
holder.tvItem.setText(data.getTitle());
}
#Override
public int getItemCount() {
return dataList.size();
}
#Override
public void changeData(List dataList) throws IllegalArgumentException{
if (dataList == null || dataList.size() <= 0)
return;
if (!(dataList.get(0) instanceof CheckboxTitlesData))
throw new IllegalArgumentException("Required data type \"CheckboxTitlesData\"");
this.dataList.clear();
this.dataList.addAll(dataList);
(new Handler(Looper.getMainLooper())).postDelayed(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
}, 100);
}
#Override
public int getRootLayout() {
return R.layout.adapter_title_checkbox;
}
#Override
public void setOnClickListener(RecyclerView.ViewHolder holder) {
holder.itemView.setOnLongClickListener((View.OnLongClickListener) holder);
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
#Bind(R.id.tvItem)
TextView tvItem;
#Bind(R.id.checkbox)
CheckBox checkBox;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
setOnClickListener(this);
}
#Override
public boolean onLongClick(View v) {
final int pos = dataList.indexOf(previousSelection);
if (pos == getAdapterPosition())
return;
if (listener != null)
listener.onMenuSelected(dataList.get(getAdapterPosition()));
CheckboxTitlesData data = dataList.get(getAdapterPosition());
data.setSelected(true);
dataList.set(getAdapterPosition(), data);
if (pos != -1) {
previousSelection.setSelected(false);
dataList.set(pos, previousSelection);
}
(new Handler(Looper.getMainLooper())).postDelayed(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
}, 100);
return true
}
}
}
Interface, u can remove the interface if you wanted, I just use this for my adapters usually for readability for other dev:
public interface GenericAdapterInterface {
void changeData(List dataList) throws Exception;
int getRootLayout();
void setOnClickListener(RecyclerView.ViewHolder holder);
}
Recycler view layout xml, add the recyclerview whr you need, this is just an eg
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llBody"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="#dimen/padding_normal"
android:paddingStart="#dimen/padding_normal">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Activity/fragment that uses the recycler view must do this
#Bind(R.id.rvMenu)
RecyclerView rvMenu;
private CheckboxTitleAdapter menuAdapter;
//Define an interface for callback on long press
public interface YourOwnInterface {
void onLonPress(Object data);
}
private void setUpRecycleView() {
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
rvMenu.setHasFixedSize(false);
rvMenu.setLayoutManager(mLayoutManager);
rvMenu.setItemAnimator(new DefaultItemAnimator());
YourOwnInterface listener = new YourOwnInterface () {
#Override
public void onLonPress(Object data) {
updateView((CheckboxTitlesData) data);
}
};
//this interface is needed wen a longpress is made adapter and the callback is given to your Acitivity/Fragment you can perform necessary opreation
menuAdapter = new CheckboxTitleAdapter(listener);
rvMenu.setAdapter(menuAdapter);
}
private void updateView(CheckboxTitlesData data) {
//perform operation on long press
}
Done it works
I have multiple recyclerViews ,which should appear after another XML view, but they just don't , am using an adapter class to manage this. after using log.v I found that the the functions itself"in Adappter class" arent called , and i don't know why ??
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.linah.movielessonapp.Detailed_Movie">
<TextView
android:id="#+id/MovieTitle"
... />
<ImageView
android:id="#+id/MovieImage"
.../>
<TextView
android:id="#+id/MovieReview"
... />
<Button
android:id="#+id/Favbutton"
... />
<TextView
android:id="#+id/Date"
... />
<TextView
android:id="#+id/Rate"
.../>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/Trailers_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/MovieReview" />
<android.support.v7.widget.RecyclerView
android:id="#+id/reviews_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/Trailers_recycler_view"
/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
public class Detailed_Movie extends AppCompatActivity {
public static List<Movie_Details> movieDetailsList = new ArrayList<>();
private String ID;
public String Trailer_OR_Review = "trailer";
private boolean noConnection;
private boolean trailersDone;
private int trailersSize;
private static MoviesDetailedAdapter mAdapter;
private RecyclerView TrailerRecyclerView, ReviewsRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed__movie);
TrailerRecyclerView = (RecyclerView) findViewById(R.id.Trailers_recycler_view);
ReviewsRecyclerView = (RecyclerView) findViewById(R.id.reviews_recycler_view);
new getData().execute("trailer");
// adapter
mAdapter = new MoviesDetailedAdapter(movieDetailsList,TrailerRecyclerView.getContext(),Trailer_OR_Review);
// mAdapter = new MoviesDetailedAdapter(movieDetailsList,ReviewsRecyclerView.getContext(),Trailer_OR_Review);
TrailerRecyclerView.setLayoutManager(new LinearLayoutManager(TrailerRecyclerView.getContext()));
// ReviewsRecyclerView.setLayoutManager(new LinearLayoutManager(ReviewsRecyclerView.getContext()));
TrailerRecyclerView.setItemAnimator(new DefaultItemAnimator());
// ReviewsRecyclerView.setItemAnimator(new DefaultItemAnimator());
noConnection = false;
if(isOnline(Detailed_Movie.this)) {
new getData().execute("trailer");
mAdapter.notifyDataSetChanged();
}
// set the adapter
TrailerRecyclerView.setAdapter(mAdapter);
prepareMovieData();
Intent i = getIntent();
// http://api.themoviedb.org/3/movie/{id}/videos
String ImgPath = "http://image.tmdb.org/t/p/w185/";
String VideoPath = "http://www.youtube.com/watch?v=";
String MovieTitle = i.getExtras().getString("title");
Toast.makeText(getApplicationContext(),MovieTitle+" is selected!", Toast.LENGTH_SHORT).show();
ImageView img = (ImageView)findViewById(R.id.MovieImage);
TextView Title = (TextView)findViewById(R.id.MovieTitle);
TextView Review = (TextView)findViewById(R.id.MovieReview);
TextView Date = (TextView)findViewById(R.id.Date);
TextView Rate = (TextView)findViewById(R.id.Rate);
Button Fav = (Button) findViewById(R.id.Favbutton);
// get data from intent
assert Title != null;
Title. setText(i.getExtras().getString("title"));
assert Review != null;
Review.setText(i.getExtras().getString("review"));
assert Rate != null;
Rate. setText(i.getExtras().getString("rate"));
assert Date != null;
Date. setText(i.getExtras().getString("date"));
ID = i.getExtras().getString("id");
String Imgurl = i.getExtras().getString("img");
// append ImgPath
switch (ImgPath = new StringBuilder()
.append(ImgPath)
.append(Imgurl)
.toString()) {
}
// append VideoPath
VideoPath = new StringBuilder()
.append(VideoPath)
.append("6uEMl2BtcqQ")
.toString();
// VideoPath = VideoPath + getString(R.string.API_KEY);
final String finalVideoPath = VideoPath;
if (Fav != null) {
Fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(finalVideoPath));
startActivity(intent);
}
});
}
Picasso.with(this)
.load(ImgPath)
.placeholder(R.drawable.loading) //this is optional the image to display while the url image is downloading
.error(R.drawable.error) //this is also optional if some error has occurred in downloading the image
.into(img);
TrailerRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), TrailerRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Movie_Details movie = movieDetailsList.get(position);
if (position < trailersSize) {
// String link = ((TextView) findViewById(R.id.Link)).getText().toString();
// String link = movie.getKey();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + movie.getKey())));
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void prepareMovieData() {
Movie_Details movie = new Movie_Details("MovieTrailer","6uEMl2BtcqQ","Linah","verynice");
movieDetailsList.add(movie);
mAdapter.notifyDataSetChanged();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
public RecyclerTouchListener(Context applicationContext, RecyclerView trailerRecyclerView, ClickListener clickListener) {
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class getData extends AsyncTask<String, Void, Void> {
...
}
}
class MoviesDetailedAdapter
public class MoviesDetailedAdapter extends RecyclerView.Adapter {
private List<Movie_Details> moviesList;
private Context context;
public String Trailer_OR_Review = "trailer";
public TextView TrailerName , Author , Content , TrailerLink ;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public MyViewHolder(View view) {
super(view);
Log.v("here","MyViewHolder");
TrailerName = (TextView) view.findViewById(R.id.Name);
Author = (TextView) view.findViewById(R.id.Author);
TrailerLink = (TextView) view.findViewById(R.id.Link);
Content = (TextView) view.findViewById(R.id.Content);
view.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
public MoviesDetailedAdapter(List<Movie_Details> moviesList,Context context, String trailerORReview) {
this.moviesList = moviesList;
this.context = context;
Trailer_OR_Review = trailerORReview;
Log.v("here","madapter");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
Log.v("here","onCreateViewHolder");
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
/*
if (Trailer_OR_Review.equals("trailers")){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
}
else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reviews_layout, parent, false);
}*/
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.v("here","onBindViewHolder");
Movie_Details movie_details = moviesList.get(position);
Log.v("here",movie_details.getContent());
Log.v("here",movie_details.getName());
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
/*
if (Trailer_OR_Review.equals("trailers")){
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
}
else{
Author.setText(movie_details.getAuthor());
Content.setText(movie_details.getContent());
}*/
}
I have implemented an abstract class that has a List View like so:
public abstract class ExampleListFragment extends ExampleFragment{
protected ListView _listView;
public ExampleListFragment () {
super();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Set Up the Bottom Bar
View view = super.onCreateView(inflater, container, savedInstanceState);
addList();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public void addList() {
_listView = new ListView(getActivity());
RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
parms.addRule(RelativeLayout.CENTER_HORIZONTAL);
parms.addRule(RelativeLayout.BELOW, R.id.tableLayout);
_listView.setLayoutParams(parms);
_listView.setClickable(true);
_listView.setFocusable(true);
_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
longListClick(i);
return true;
}
});
_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listClick(i);
}
});
_layout.addView(_listView);
}
public abstract void longListClick(int pos);
public abstract void listClick(int pos);
}
I then have a class that inherits from this to implement the abstract methods which should be called when clicking an item in the list
public class TwitterFragment extends ExampleListFragment {
private TwitterAdapter _adapter;
//...
#Override
public void onSelected() {
_adapter = new TwitterAdapter(getActivity());
populateAdapter();
}
private void populateAdapter() {
showLoadingTweets();
new TwitterGetTimelineTask().execute(username); //fills adapter with Twitter status info...
}
#Override
public void longListClick(int pos) {
Toast toast = Toast.makeText(getActivity(),String.format("You have clicked item number: %d",pos),
Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void listClick(int pos) {
Toast toast = Toast.makeText(getActivity(),String.format("You have clicked item number: %d",pos),
Toast.LENGTH_SHORT);
toast.show();
}
//...
class TwitterGetTimelineTask extends AsyncTask<String, String, String> {
//...
}
}
However, whenever I click on an Item, it does not appear to even enter onItemClick functions.
Any ideas? help much appreciated.
*EDIT*
As requested, here is the code for my Adapter
public class TwitterAdapter extends BaseAdapter {
private ArrayList<StatusDetails> _statusDetailsArrayList;
private LayoutInflater _inflater;
public TwitterAdapter(Context context) {
_statusDetailsArrayList = new ArrayList<StatusDetails>();
_inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return _statusDetailsArrayList.size();
}
#Override
public Object getItem(int i) {
return _statusDetailsArrayList.get(i);
}
#Override
public long getItemId(int i) {
return _statusDetailsArrayList.get(i).get_id();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = _inflater.inflate(R.layout.twitter_layout, null);
holder = new ViewHolder();
holder.img_icon = (ImageView) view.findViewById(R.id.statusImage);
holder.text_line1 = (TextView) view.findViewById(R.id.statusText);
holder.text_line2 = (TextView) view.findViewById(R.id.statusDateText);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Bitmap bmp = _statusDetailsArrayList.get(i).get_profile();
if (bmp == null) {
holder.img_icon.setImageResource(R.drawable.ic_action_twitter);
} else {
holder.img_icon.setImageBitmap(bmp);
}
holder.text_line1.setText(_statusDetailsArrayList.get(i).get_text());
holder.text_line2.setText(_statusDetailsArrayList.get(i).get_date());
return view;
}
public void addStatus(StatusDetails details) {
_statusDetailsArrayList.add(details);
}
public void setStatuses(ArrayList<StatusDetails> details) {
_statusDetailsArrayList = details;
}
public ArrayList<StatusDetails> getEvents() {
return _statusDetailsArrayList;
}
public void removeAll() {
_statusDetailsArrayList.clear();
}
private class ViewHolder {
ImageView img_icon;
TextView text_line1;
TextView text_line2;
}
}
And if needed, the XML of the layout of each list
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/statusImage"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Status"
android:id="#+id/statusText"
android:layout_alignParentTop="true"
android:autoLink="web"
android:textColor="#android:color/white"
android:layout_toRightOf="#+id/statusImage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_below="#id/statusText"
android:text="Date"
android:id="#+id/statusDateText"
android:layout_alignBottom="#+id/statusImage"
android:layout_toRightOf="#+id/statusImage" />
Thanks.