Edit
Solved issue by removing two lines
holder.checkbox.setChecked(mListenerList.get(position).isSelected());
holder.checkbox.setChecked(mListenerList.get(position).isSelected2());
And By Adding
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
I am not editing my original code for future developers.
Main Question before Edit Start from Here
I am working on fantasy cricket app where I am selecting the captain and vice captain from a list of 11 player.
I am using a checkbox for selecting the captain and vice captain.
The selection of checkbox is working fine with my code, but the issue is when I select 1st player as a captain(C) and 2nd player as Vice-Captain(VC) and then scroll the list the checkbox state is changing and showing other player selected.
So is there any right way to do that thing?
I have tried many way they are working when there is single checkbox but in my case there is two and only one can be select from the list.
Please refer to the attached screenshots on the bottom for clarity.
Adapter Class
public class AdapterFinalTeamList extends RecyclerView.Adapter<AdapterFinalTeamList.MyViewHolder> {
private List<BeanDBTeam> mListenerList;
Context mContext;
private CheckBox lastChecked = null;
private int lastCheckedPos = 0;
private CheckBox lastChecked2 = null;
private int lastCheckedPos2 = 0;
private RadioButton lastCheckedRB = null;
private RadioButton lastCheckedRB1 = null;
TextView PreviousCaptain = null;
TextView PreviousVC = null;
public AdapterFinalTeamList(List<BeanDBTeam> mListenerList, Context context) {
mContext = context;
this.mListenerList = mListenerList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_PlayerName,tv_SelectCaptain,tv_SelectViceCaptain, tv_PlayerTeamName, tv_PlayerPoints,tv_TeamNumber;
ImageView im_PlayerImage,im_onetwox;
CheckBox checkbox,checkbox2;
RadioGroup radiogroup;
RadioButton radio,radio2;
public MyViewHolder(View view) {
super(view);
tv_PlayerName =view.findViewById(R.id.tv_PlayerName);
tv_PlayerTeamName = view.findViewById(R.id.tv_PlayerTeamName);
tv_PlayerPoints = view.findViewById(R.id.tv_PlayerPoints);
im_PlayerImage = view.findViewById(R.id.im_PlayerImage);
im_onetwox = view.findViewById(R.id.im_onetwox);
tv_TeamNumber = view.findViewById(R.id.tv_TeamNumber);
tv_SelectViceCaptain = view.findViewById(R.id.tv_SelectViceCaptain);
tv_SelectCaptain= view.findViewById(R.id.tv_SelectCaptain);
checkbox= view.findViewById(R.id.checkbox);
checkbox2= view.findViewById(R.id.checkbox2);
radiogroup= view.findViewById(R.id.radiogroup);
radio= view.findViewById(R.id.radio);
radio2= view.findViewById(R.id.radio2);
}
}
#Override
public int getItemCount() {
return mListenerList.size();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_final_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
String id = mListenerList.get(position).getMatchId();
String arrayList = (mListenerList.get(position).getPlayerData());
try {
JSONObject job = new JSONObject(arrayList);
String PlayerName = job.getString("name");
String PlayerImage = job.getString("image");
String PlayerPoints = job.getString("player_points");
String PlayerCredit = job.getString("credit_points");
String TeamShortName = job.getString("team_short_name");
String team_number = job.getString("team_number");
String player_shortname = job.getString("player_shortname");
holder.tv_TeamNumber.setText(team_number);
// PlayerTeam= job.getString("short_name");
holder.tv_PlayerName.setText(PlayerName);
holder.tv_PlayerPoints.setText(PlayerPoints);
holder.tv_PlayerTeamName.setText(TeamShortName);
Glide.with(activity).load(Config.PLAYERIMAGE + PlayerImage)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.im_PlayerImage);
} catch (JSONException e) {
e.printStackTrace();
}
holder.checkbox.setChecked(mListenerList.get(position).isSelected());
holder.checkbox.setTag(new Integer(position));
holder.checkbox.setChecked(mListenerList.get(position).isSelected2());
holder.checkbox2.setTag(new Integer(position));
holder.checkbox.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
int clickedPos = ((Integer) cb.getTag()).intValue();
holder.checkbox2.setChecked(false);
if (cb.isChecked()) {
if (lastChecked != null) {
mListenerList.get(lastCheckedPos).setSelected(false);
lastChecked.setChecked(false);
}
else if (clickedPos==position){
lastCheckedPos = clickedPos;
lastChecked = cb;
lastChecked.setChecked(true);
}
lastCheckedPos = clickedPos;
lastChecked = cb;
} else
lastChecked = null;
try {
lastChecked.setChecked(true);
}
catch (Exception e){
e.printStackTrace();
}
mListenerList.get(clickedPos).setSelected(cb.isChecked());
CaptainId = mListenerList.get(position).getPlayerId();
}
});
holder.checkbox2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
int clickedPos = ((Integer) cb.getTag()).intValue();
holder.checkbox.setChecked(false);
if (cb.isChecked()) {
if (lastChecked2 != null) {
lastChecked2.setChecked(false);
mListenerList.get(lastCheckedPos2).setSelected(false);
}
else if (clickedPos==position){
lastChecked2 = cb;
lastCheckedPos2 = clickedPos;
lastChecked2.setChecked(true);
}
lastChecked2 = cb;
lastCheckedPos2 = clickedPos;
} else
lastChecked2 = null;
try{
lastChecked2.setChecked(true);
}
catch (Exception e){
e.printStackTrace();
}
mListenerList.get(clickedPos).setSelected2(cb.isChecked());
ViceCaptainId = mListenerList.get(position).getPlayerId();
}
});
}
}
adapter_final_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res /android"
android:layout_width="match_parent"
android:background="#color/white"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:padding="5dp"
android:id="#+id/RL_PlayerListMain"
android:elevation="0dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_TeamNumber"
android:visibility="invisible"/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/logo"
android:layout_centerVertical="true"
android:id="#+id/im_PlayerImage"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:id="#+id/RL_Name"
android:layout_toRightOf="#+id/im_PlayerImage"
android:layout_marginLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Player Name"
android:id="#+id/tv_PlayerName"
android:textColor="#1e1e1e"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_below="#+id/tv_PlayerName">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IND"
android:layout_gravity="center"
android:layout_marginRight="5dp"
android:id="#+id/tv_PlayerTeamName"
android:textColor="#1e1e1e"
/>
<View
android:layout_width="1dp"
android:layout_height="10dp"
android:layout_gravity="center"
android:background="#8e8e8e"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="55 Points"
android:layout_gravity="center"
android:id="#+id/tv_PlayerPoints"
android:textColor="#8e8e8e"
android:layout_marginLeft="5dp"
/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:id="#+id/RL_Credit"
android:layout_alignParentRight="true">
<TextView
android:layout_width="40dp"
android:layout_height="40dp"
android:text="C"
android:padding="10dp"
android:textAlignment="center"
android:gravity="center"
android:visibility="gone"
android:layout_centerVertical="true"
android:background="#drawable/circle_captain_vc_back"
android:id="#+id/tv_SelectCaptain"
android:textColor="#1e1e1e"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/tv_SelectViceCaptain"
android:layout_centerVertical="true"
android:visibility="visible"
android:text="C"
android:textColor="#1e1e1e"
android:gravity="center"
android:button="#android:color/transparent"
android:background="#drawable/radio_selector"
android:id="#+id/checkbox"/>
<CheckBox
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/checkbox"
android:layout_centerVertical="true"
android:visibility="visible"
android:text="VC"
android:layout_marginLeft="5dp"
android:textColor="#1e1e1e"
android:gravity="center"
android:button="#android:color/transparent"
android:background="#drawable/radio_vc_selector"
android:id="#+id/checkbox2"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/onex_icon"
android:visibility="invisible"
android:layout_centerHorizontal="true"
android:id="#+id/im_onetwox"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radiogroup"
android:visibility="gone"
android:layout_marginTop="10dp"
android:layout_below="#+id/im_onetwox"
android:orientation="horizontal">
<RadioButton
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/tv_SelectViceCaptain"
android:layout_centerVertical="true"
android:visibility="visible"
android:text="C"
android:layout_marginRight="10dp"
android:gravity="center"
android:background="#drawable/radio_selector"
android:button="#android:color/transparent"
android:id="#+id/radio"/>
<RadioButton
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/checkbox"
android:layout_centerVertical="true"
android:visibility="visible"
android:text="VC"
android:gravity="center"
android:background="#drawable/radio_vc_selector"
android:button="#android:color/transparent"
android:id="#+id/radio2"/>
</RadioGroup>
<TextView
android:layout_width="40dp"
android:layout_height="40dp"
android:text="VC"
android:textAlignment="center"
android:gravity="center"
android:visibility="gone"
android:padding="10dp"
android:layout_toRightOf="#+id/tv_SelectCaptain"
android:layout_centerVertical="true" android:background="#drawable/circle_captain_vc_back"
android:id="#+id/tv_SelectViceCaptain"
android:textColor="#1e1e1e"
android:layout_marginLeft="10dp"
/>
</RelativeLayout>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#8e8e8e"
android:layout_marginTop="5dp"
android:layout_marginBottom="2dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:layout_below="#+id/RL_PlayerListMain"/>
</RelativeLayout>
Selecting C and VC
After scrolling top to bottom and bottom to top
Please ignore Radio group. My code is working fine with checkbox, it's only creating issues when scrolling.
For checkbox you need to use checkbox.OnCheckedChangeListener() instead of checkbox.setOnClickListener()
Follow this steps
add a new Boolean variable in your BeanDBTeam class
public class BeanDBTeam
{
boolean isChecked;
public boolean getisChecked() {
return isChecked;
}
public void setIsChecked(boolean flag) {
isChecked= flag;
}
}
Now inside you onBindViewHolder() add below code
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
BeanDBTeam bean = mListenerList.get(position).getisChecked()
// check here the flag and status of checkbox based on flag
holder.checkbox2.setChecked(bean.getisChecked());
holder.checkbox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
// set flag of checkbox status in your list when user check or uncheck the checkbox
bean.setIsChecked(isChecked);
notifyDataChanged();
}
});
}
This is what recycling behaviour is, You can use other answer that are also correct but as you are having limited entries in your list you can actually disable recycling your recyclerview. Use below code in your adapter:
#Override
public void onBindViewHolder(final CommentViewHolder viewHolder, final int position) {
viewHolder.setIsRecyclable(false);
}
As #Nilesh suggested you , to use the Bean class for checkbox state remember functionality like below:
/**
* CheckType ==>>1 For the first checkbox
* CheckType ==>>2 For the second checkbox
* CheckType ==>>0 For the None
*/
public class BeanDBTeam
{
int checkType;
public int getCheckType() {
return checkType;
}
public void setCheckType(int checkType) {
this.checkType = checkType;
}
}
Inside the MyViewHolder you need to apply the setOnCheckedChangeListener listener and get position from the getAdapterPosition() like below
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_PlayerName, tv_SelectCaptain, tv_SelectViceCaptain, tv_PlayerTeamName, tv_PlayerPoints, tv_TeamNumber;
ImageView im_PlayerImage, im_onetwox;
CheckBox checkbox, checkbox2;
RadioGroup radiogroup;
RadioButton radio, radio2;
public MyViewHolder(View view) {
super(view);
tv_PlayerName = view.findViewById(R.id.tv_PlayerName);
tv_PlayerTeamName = view.findViewById(R.id.tv_PlayerTeamName);
tv_PlayerPoints = view.findViewById(R.id.tv_PlayerPoints);
im_PlayerImage = view.findViewById(R.id.im_PlayerImage);
im_onetwox = view.findViewById(R.id.im_onetwox);
tv_TeamNumber = view.findViewById(R.id.tv_TeamNumber);
tv_SelectViceCaptain = view.findViewById(R.id.tv_SelectViceCaptain);
tv_SelectCaptain = view.findViewById(R.id.tv_SelectCaptain);
checkbox = view.findViewById(R.id.checkbox);
checkbox2 = view.findViewById(R.id.checkbox2);
radiogroup = view.findViewById(R.id.radiogroup);
radio = view.findViewById(R.id.radio);
radio2 = view.findViewById(R.id.radio2);
/**
* NOW WE APPLY THE setOnCheckedChangeListener functionality for the checkboxlistener
*/
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set flag of checkbox status in your list when user check or uncheck the checkbox
if (checkbox) {
YOUR_ARRAYLIST.get(getAdapterPosition()).setCheckType(1);
}
else {
YOUR_ARRAYLIST.get(getAdapterPosition()).setCheckType(0);
}
notifyDataChanged();
}
});
checkbox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set flag of checkbox status in your list when user check or uncheck the checkbox
if (checkbox) {
YOUR_ARRAYLIST.get(getAdapterPosition()).setCheckType(2);
}
else {
YOUR_ARRAYLIST.get(getAdapterPosition()).setCheckType(0);
}
notifyDataChanged();
}
});
}
}
And inside the onBindViewHolder we need to set the Checkbox according to the selection like below
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
BeanDBTeam bean = mListenerList.get(position).getisChecked()
// check here the flag and status of checkbox based on flag
if(bean.getCheckType()==0) {
holder.checkbox.setChecked(false);
holder.checkbox2.setChecked(false);
}
else if(bean.getCheckType()==1) {
holder.checkbox.setChecked(true);
holder.checkbox2.setChecked(false);
}
else if(bean.getCheckType()==2) {
holder.checkbox.setChecked(false);
holder.checkbox2.setChecked(true);
}
}
Related
I am developing a shopping cart and I want to increase the number of Items purchased when a user clicks a button in each row of the recyclerview.
I have tried to increment the edit text when a user clicks the increase button but it updates value of all edittext in the recyclerview.
XML
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatButton
android:layout_weight="1"
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="Add"
android:textColor="#FFF" />
<android.support.v7.widget.AppCompatButton
android:layout_weight="1"
android:id="#+id/decrease"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:textColor="#FFF" />
<EditText
android:layout_weight="1"
android:id="#+id/numberOfItems"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/add"
android:inputType="phone" />
<android.support.v7.widget.AppCompatButton
android:layout_weight="1"
android:layout_marginLeft="10dp"
android:id="#+id/increase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/numberOfItems"
android:text="+"
android:textColor="#FFF" />
<android.support.v7.widget.AppCompatButton
android:layout_weight="1"
android:layout_marginLeft="10dp"
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#dc3434"
android:text="Remove"
android:textColor="#FFF" />
</LinearLayout>
adapter
public class BreadAdapter extends RecyclerView.Adapter<BreadAdapter.ViewHolder> {
public List<BreadModel> breads;
Context context;
private int quntity= 0;
public BreadAdapter(List<BreadModel> breads, Context context) {
this.breads = breads;
this.context = context;
}
#NonNull
#Override
public BreadAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_bread_recyclerview, parent, false));
}
#Override
public void onBindViewHolder(#NonNull final BreadAdapter.ViewHolder holder, int position) {
final BreadModel bread_title = breads.get(position);
holder.tv_title.setText(bread_title.getName());
holder.tv_price.setText(String.valueOf(bread_title.getPrice()));
Log.i("info", bread_title.getImg());
GlideApp.with(context)
.load(bread_title.getImg())
holder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quntity= quntity+ 1;
holder.et_numberOfItems.setText(String.valueOf(quntity));
}
});
}
public void update(){
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return breads.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final EditText et_numberOfItems;
TextView tv_title;
TextView tv_price;
ImageView img_breads;
CardView cv_bread;
AppCompatButton add;
AppCompatButton remove;
AppCompatButton increase;
AppCompatButton decrease;
public ViewHolder(View itemView) {
super(itemView);
et_numberOfItems = (EditText) itemView.findViewById(R.id.numberOfItems);
tv_title = (TextView) itemView.findViewById(R.id.tv_title);
tv_price = (TextView) itemView.findViewById(R.id.tv_price);
img_breads = (ImageView) itemView.findViewById(R.id.breadImageViews);
cv_bread = (CardView) itemView.findViewById(R.id.breadCardView);
add = (AppCompatButton) itemView.findViewById(R.id.add);
remove = (AppCompatButton) itemView.findViewById(R.id.remove);
increase = (AppCompatButton) itemView.findViewById(R.id.increase);
decrease = (AppCompatButton) itemView.findViewById(R.id.decrease);
}
}
}
Here is my adapter code please have look at it and help me thanks.
This is the screen shot
If I click on the plus(+) button it increases the number of item on all the edittext instead of that particular item
I am facing two issues.
Radio buttons in radiogroup loosing state: when I click yes or no and scroll down the list view it looses the radiobutton value which is checked. I tried many ways to fix it but unable to achieve.
Submit button validation(Please refer image four): list of questions user should select either yes or no before clicking on submit button, if user click on submit button without selecting either yes or no it should them a toast message. all the questions should be selected with either yes or no. More specific each radiogroup should give me yes or no, not empty string.
Thanks in advance.
Custom Adapter
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.list_items, null);
TextView question = (TextView) view.findViewById(R.id.question);
final RadioButton yes = (RadioButton) view.findViewById(R.id.yes);
final RadioButton no = (RadioButton) view.findViewById(R.id.no);
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (yes.isChecked()) {
yes.setBackgroundColor(Color.GREEN);
no.setBackgroundColor(Color.BLACK);
}
if (no.isChecked()){
no.setBackgroundColor(Color.rgb(255,165,0));
yes.setBackgroundColor(Color.BLACK);
}
}
});
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "1");
}
});
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "2");
}
});
question.setText(questionsList[i]);
return view;
}
Main Activity
public class MainActivity extends AppCompatActivity {
ListView simpleList;
String[] questions;
Button submit,submit1;
FileOutputStream fstream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questions = getResources().getStringArray(R.array.questions);
simpleList = (ListView) findViewById(R.id.simpleListView);
View footerView = getLayoutInflater().inflate(R.layout.footer,null);
submit = (Button) footerView.findViewById(R.id.submit1);
simpleList.addFooterView(footerView);
View headerView = getLayoutInflater().inflate(R.layout.header, null);
simpleList.addHeaderView(headerView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
try {
fstream = openFileOutput("user_answer", Context.MODE_PRIVATE);
fstream.write(message.getBytes());
fstream.close();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
Intent inent = new Intent(v.getContext(), DetailsActivity.class);
startActivity(inent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
XML main layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/Black"
android:padding="10dp">
<RelativeLayout
android:id="#+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#drawable/round_relativelayout"
>
<ListView
android:id="#+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/Black"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
/>
</RelativeLayout>
List item XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#color/LightGrey">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="#dimen/activity_horizontal_margin"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout 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=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:background="#color/Black"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textColor="#color/White"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="#color/Black"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textColor="#color/White"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
Image oneImage twoImage threeImage four with submit button
Try the following:
1) MainActivity_.class:-----
public class MainActivity_ extends AppCompatActivity {
private ListView lv;
private CustomAdapter customAdapter;
private String[] questions;
private Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout8);
questions = new String[10];
for(int i = 0 ; i<10 ; i++){
questions[i] = "Q " + i;
}
lv = (ListView) findViewById(R.id.lv);
customAdapter = new CustomAdapter(getApplicationContext() , questions);
lv.setAdapter(customAdapter);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean found_unanswered = false;
if(customAdapter != null){
for(int i = 0 ; i<customAdapter.getSelectedAnswers().size() ; i++){
if(customAdapter.getSelectedAnswers().get(i).equals("3")){
found_unanswered = true;
break;
}
}
}
if(!found_unanswered){
Toast.makeText(getApplicationContext() , "All Answered" , Toast.LENGTH_LONG).show();
//Go to other activity
}
}
});
}
}
2) CustomAdapter.class:------
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("3");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return questionsList[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (convertView == null) {
if (inflter != null) {
view = inflter.inflate(R.layout.list_items, null);
}
}
TextView question = (TextView) view.findViewById(R.id.question);
question.setText(questionsList[i]);
// initialize/ restore UI Radio Button State
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
RadioButton rb_yes = (RadioButton) rg.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) rg.findViewById(R.id.no);
if(selectedAnswers.get(i).equals("1")){
rg.check(R.id.yes);
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
}else if(selectedAnswers.get(i).equals("2")){
rg.check(R.id.no);
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
}else{
// no answer.
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.GRAY);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb_yes = (RadioButton) group.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) group.findViewById(R.id.no);
switch (checkedId){
case R.id.yes:
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
selectedAnswers.set(i, "1");
break;
case R.id.no:
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
selectedAnswers.set(i, "2");
break;
}
}
});
return view;
}
public List<String> getSelectedAnswers(){
return selectedAnswers;
}
}
3) layout8.xml:------
<?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="match_parent"
android:orientation="vertical"
android:weightSum="100">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="80"
android:id="#+id/lv">
</ListView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/lv"
android:layout_weight="20"
android:text="Submit"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/submit"/>
</LinearLayout>
4) list_items.xml:-----
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout 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=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
</LinearLayout>
Try this.
Use ViewHolder so it does not lose the data set
Custom Adapter class
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = inflter.inflate(R.layout.list_items, null);
viewHolder = new ViewHolder();
ViewHoldwe.question = (TextView) view.findViewById(R.id.question);
viewHolder.yes = (RadioButton) view.findViewById(R.id.yes);
viewHolder.no = (RadioButton) view.findViewById(R.id.no);
viewHolder.rg = (RadioGroup) view.findViewById(R.id.radio_group);
view.setTag(viewHolder)
}else{
viewHolder = (ViewHolder) view.getTag();
viewHolder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (viewHolder.yes.isChecked()) {
viewHolder.yes.setBackgroundColor(Color.GREEN);
viewHolder.no.setBackgroundColor(Color.BLACK);
}
if (viewHolder.no.isChecked()){
viewHolder.no.setBackgroundColor(Color.rgb(255,165,0));
viewHolder.yes.setBackgroundColor(Color.BLACK);
}
}
});
viewHolder.yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "1");
}
});
viewHolder.no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "2");
}
});
question.setText(questionsList[i]);
}
return view;
}
Make a private inner class
private class ViewHolder{
RadioButton yes;
TextView question;
RadioButton no ;
RadioGroup rg;
}
Based on my previous question , I have a problem with onClick on CardView in my RecyclerView. I need to change the card layout when the CardView is clicked with another card layout xml. I follow this and this this but its not work. I dont too understand how to declare one CardView layout again in my code. Here my Code :
Adapter.Java
public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int view1 = 0;
public static final int view2 = 1;
private static OnRecyclerViewItemClickedListener recyclerViewItemClickedListener;
public void setOnRecyclerViewClickedListener (OnRecyclerViewItemClickedListener l) {
recyclerViewItemClickedListener = l;
}
public interface OnRecyclerViewItemClickedListener {
void OnRecyclerViewItemClicked(int position);
void OnRecyclerViewItemBind(ViewHolder holder, int position);
int OnRecyclerViewItemCount();
}
public Adapter() {
super();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == view1) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.table_item_empty, parent, false);
return new ViewHolder(itemView);
}
else if (viewType == view2) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.table_item_occupied, parent, false);
return new ViewHolder2(itemView);
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
recyclerViewItemClickedListener.OnRecyclerViewItemBind((ViewHolder) holder, position);
}
#Override
public int getItemCount() {
return recyclerViewItemClickedListener.OnRecyclerViewItemCount();
}
public int getItemViewType() { return recyclerViewItemClickedListener.getItemViewType(); }
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txt_no_table;
public TextView txt_no_table_occ;
public TextView txt_pax_occ;
public TextView txt_guest_name_occ;
public TextView txt_bill_occ;
public Chronometer txt_time_occ;
public CardView cardview_table;
public LinearLayout title_layout;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txt_no_table = (TextView) itemView.findViewById(R.id.txt_no_table_empty);
txt_no_table_occ = (TextView) itemView.findViewById(R.id.txt_no_table);
txt_pax_occ = (TextView) itemView.findViewById(R.id.txt_pax);
txt_guest_name_occ = (TextView)itemView.findViewById(R.id.txt_guestname);
txt_bill_occ = (TextView) itemView.findViewById(R.id.txt_bill);
txt_time_occ = (Chronometer) itemView.findViewById(R.id.txt_time);
cardview_table = (CardView) itemView.findViewById(R.id.table_card_empty);
title_layout = (LinearLayout) itemView.findViewById(R.id.table_ll1);
}
#Override
public void onClick(View itemView) {
recyclerViewItemClickedListener.OnRecyclerViewItemClicked(getAdapterPosition());
}
}
public class ViewHolder2 extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txt_no_table2;
public TextView txt_pax2;
public TextView txt_guest_name2;
public TextView txt_bill2;
public TextView txt_time2;
public ViewHolder2 (View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txt_no_table2 = (TextView) itemView.findViewById(R.id.txt_no_table_);
txt_pax2 = (TextView) itemView.findViewById(R.id.txt_pax_);
txt_guest_name2 = (TextView)itemView.findViewById(R.id.txt_guestname_);
txt_bill2 = (TextView) itemView.findViewById(R.id.txt_bill_);
txt_time2 = (TextView) itemView.findViewById(R.id.txt_time_);
}
#Override
public void onClick(View itemView) {
recyclerViewItemClickedListener.OnRecyclerViewItemClicked(getAdapterPosition());
}
}
}
Here My Activity :
adapter.setOnRecyclerViewClickedListener(new Adapter.OnRecyclerViewItemClickedListener() {
#Override
public void OnRecyclerViewItemClicked(int position) {
try {
JSONObject currTable = filteredTableList.getJSONObject(position);
if (currTable.has("selected")) {
currTable.put("selected", !currTable.getBoolean("selected"));
} else {
currTable.put("selected",true);
}
adapter.notifyItemChanged(position);
} catch (JSONException e) {
e.printStackTrace();
}
try
{
Toast.makeText(TableActivity.this, filteredTableList.getJSONObject(position).getString("tischnr"), Toast.LENGTH_SHORT).show();
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void OnRecyclerViewItemBind(Adapter.ViewHolder holder, int position) {
try {
JSONObject currTable = filteredTableList.getJSONObject(position);
holder.txt_no_table.setText(currTable.getString("tischnr"));
holder.txt_guest_name_occ.setText("");
holder.txt_pax_occ.setText("");
holder.txt_bill_occ.setText("");
int queasy33Index = ProgramMethod.getJSONArrayIndex(queasy33List,"number2", currTable.getInt("tischnr"));
if (queasy33Index >= 0) {
holder.txt_guest_name_occ.setText(queasy33List.getJSONObject(queasy33Index).getString("char2"));
holder.txt_pax_occ.setText(queasy33List.getJSONObject(queasy33Index).getString("number3"));
}
if (currTable.has("selected") && currTable.getBoolean("selected")) {
holder.itemView.setBackgroundResource(R.color.colorRedTableOcc);
holder.txt_no_table.setVisibility(View.INVISIBLE);
holder.txt_no_table_occ.setVisibility(View.VISIBLE);
holder.txt_bill_occ.setVisibility(View.VISIBLE);
holder.txt_pax_occ.setVisibility(View.VISIBLE);
holder.txt_time_occ.setVisibility(View.VISIBLE);
holder.txt_guest_name_occ.setVisibility(View.VISIBLE);
} else {
holder.itemView.setBackgroundResource(R.color.colorTableGreen);
holder.txt_no_table.setVisibility(View.VISIBLE);
holder.txt_no_table_occ.setVisibility(View.INVISIBLE);
holder.txt_bill_occ.setVisibility(View.INVISIBLE);
holder.txt_pax_occ.setVisibility(View.INVISIBLE);
holder.txt_time_occ.setVisibility(View.INVISIBLE);
holder.txt_guest_name_occ.setVisibility(View.INVISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int OnRecyclerViewItemCount() {
return filteredTableList.length();
}
});
My table_item_empty.xml (first layout) :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/table_card_empty"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#color/colorTableGreen"
app:cardCornerRadius="15dp"
app:cardElevation="5dp"
android:layout_margin="3dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
android:gravity="center">
<RelativeLayout
android:id="#+id/table_rl1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/table_ll1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">
<TextView
android:id="#+id/txt_no_table"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="15dp"
android:gravity="center"
android:textColor="#color/colorWhite"
android:visibility="invisible"/>
</LinearLayout>
<TextView
android:id="#+id/txt_pax"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:text="5"
android:textSize="10dp"
android:textColor="#color/colorWhite"
android:drawableLeft="#drawable/ic_airline_seat_recline_normal_white_18dp"
android:visibility="invisible"/>
<TextView
android:id="#+id/txt_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10:00"
android:textSize="10dp"
android:textColor="#color/colorWhite"
android:drawableLeft="#drawable/ic_access_time_white_18dp"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/txt_pax"
android:layout_marginStart="2dp"
android:visibility="invisible"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/table_rl2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/table_rl1">
<TextView
android:id="#+id/txt_guestname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:text="Budi"
android:textSize="10dp"
android:textColor="#color/colorWhite"
android:drawableLeft="#drawable/ic_supervisor_account_white_18dp"
android:visibility="invisible"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/table_rl2">
<TextView
android:id="#+id/txt_bill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10000"
android:drawableLeft="#drawable/ic_attach_money_white_18dp"
android:textSize="10dp"
android:textColor="#color/colorWhite"
android:layout_marginStart="1dp"
android:visibility="invisible"/>
</RelativeLayout>
<TextView
android:id="#+id/txt_no_table_empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12"
android:textSize="25dp"
android:gravity="center_vertical|center_horizontal"
android:textColor="#color/colorWhite"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
App looks like :
My code make a first layout gone when i clicked but i want to show/change another card layout.
This is CardView1 Looks like :
Another CardView xml (CardView2) :
EDITED :
I trick it. Now when one or more item clicked, it will change the view into like this :
But i still want to try with two different layout.xml view when item clicked. Its work because i only 'play' with 'INVISIBLE' and 'VISIBLE' in element on one layout, not the xml.
[EDITED] :
I'm still try to make my RecyclerView with two Layout view. I improve my Adapter like above. I follow this but i get a litle problem. In my Acivity, i call my itemView from ViewHolder1 with holder (example: holder.txt_time....) like my code above. I want to know how i can call my second holder (ViewHolder2) in my Activity? I try to make hard code with add some listener but its not work for me :(
Maybe somebody can help and guide me to fix my code. Every answer will helpful for me. Thanks before.
I have a recycler view. I have added an expandable view in the list item view. On a click it expands and show the layout. But now I want to close it on click of same item if its open.
Now if I click on 1st item the layout gets expanded and then if i click on 2nd item layout for 2nd item gets expanded and layout for 1st item gets closed.
I have followed this link :
RecyclerView expand/collapse items
Adapter:
public class BookingsAdapter extends RecyclerView.Adapter<BookingsAdapter.MyViewHolder> implements View.OnClickListener{
private int expandedPosition = -1;
private List<Bookings> bookingsList;
int status;
Context context;
public interface OnItemClickListener {
void onItemClick(Events item);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView eventName,eventType,eventDateTime,userName;
public RelativeLayout expandLayout;
public CardView cardView;
public MyViewHolder(View view) {
super(view);
eventName = (TextView) view.findViewById(R.id.text_eventName);
eventType = (TextView) view.findViewById(R.id.textView_EventType);
eventDateTime = (TextView) view.findViewById(R.id.text_dateTime);
userName = (TextView) view.findViewById(R.id.text_userName);
expandLayout = (RelativeLayout) view.findViewById(R.id.expandLayout);
cardView = (CardView) view.findViewById(R.id.card_view);
}
}
public BookingsAdapter(ArrayList<Bookings> bookingsList,Context context) {
this.bookingsList = bookingsList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.bookings_card, parent, false);
MyViewHolder holder = new MyViewHolder(itemView);
// Sets the click adapter for the entire cell
// to the one in this class.
holder.itemView.setOnClickListener(BookingsAdapter.this);
holder.itemView.setTag(holder);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bookings bookings = bookingsList.get(position);
holder.eventName.setText(bookings.getEventName());
holder.eventType.setText(bookings.getEventType());
holder.eventDateTime.setText(bookings.getEventDateTime());
holder.userName.setText(bookings.getUserName());
if (position == expandedPosition) {
holder.expandLayout.setVisibility(View.VISIBLE);
} else {
holder.expandLayout.setVisibility(View.GONE);
}
}
#Override
public void onClick(View view) {
MyViewHolder holder = (MyViewHolder) view.getTag();
Bookings bookingsItem = bookingsList.get(holder.getPosition());
// Check for an expanded view, collapse if you find one
if (expandedPosition >= 0) {
int prev = expandedPosition;
notifyItemChanged(prev);
}
// Set the current position to "expanded"
expandedPosition = holder.getPosition();
notifyItemChanged(expandedPosition);
Toast.makeText(context, "Clicked: "+ bookingsItem.getEventName(), Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return bookingsList.size();
}
}
Layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#android:color/white"
android:layout_marginTop="05dp"
android:layout_marginRight="05dp"
android:layout_marginLeft="05dp"
card_view:cardElevation="2dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/parentLayout">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="90dp"
android:id="#+id/detailsLayout">
<RelativeLayout
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="05dp"
android:layout_marginBottom="05dp"
android:id="#+id/eventLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event name"
android:id="#+id/text_eventName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="14sp"
android:textColor="#android:color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="("
android:id="#+id/textView26"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/textView_EventType"
android:textSize="12sp"
android:textColor="#color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date and time"
android:id="#+id/text_dateTime"
android:layout_below="#+id/textView26"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="05dp"
android:textSize="12sp"
android:textColor="#color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event type"
android:id="#+id/textView_EventType"
android:layout_below="#+id/text_eventName"
android:layout_toRightOf="#+id/textView26"
android:layout_toEndOf="#+id/textView26"
android:layout_marginTop="05dp"
android:textSize="12sp"
android:textColor="#color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=")"
android:id="#+id/textView29"
android:layout_alignTop="#+id/textView_EventType"
android:layout_toRightOf="#+id/textView_EventType"
android:layout_toEndOf="#+id/textView_EventType"
android:textSize="12sp"
android:textColor="#color/colorAccent" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/place_autocomplete_separator"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:layout_alignParentTop="true">
</View>
</RelativeLayout>
<View
android:layout_width="3dp"
android:layout_height="wrap_content"
android:background="#color/grey">
</View>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/eventLayout"
android:layout_toRightOf="#+id/eventLayout"
android:layout_toEndOf="#+id/eventLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/eventLayout"
android:id="#+id/profilepicLayout">
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:src="#drawable/ic_person_black_48dp"
android:id="#+id/profileImage"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="false"
android:background="#drawable/circle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:id="#+id/text_userName"
android:layout_below="#+id/profileImage"
android:layout_marginTop="05dp"
android:textColor="#android:color/black"
android:textSize="12sp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textAlignment="center" />
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false"
android:layout_below="#+id/detailsLayout"
android:id="#+id/expandLayout"
android:visibility="gone">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/place_autocomplete_separator"></View>
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:id="#+id/imageView12"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#drawable/ic_call_black_18dp"
android:layout_centerVertical="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="05dp"
android:layout_marginBottom="05dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:id="#+id/imageView13"
android:layout_alignTop="#+id/imageView12"
android:layout_centerHorizontal="true"
android:background="#drawable/ic_textsms_black_18dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:id="#+id/imageView14"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="30dp"
android:layout_marginEnd="30dp"
android:background="#drawable/ic_chat_black_18dp"
android:layout_centerVertical="true"
android:layout_alignTop="#+id/imageView13" />
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
EDIT: I have added boolean variable in class and did this. Noting happens. Layout dose not get close when I click on item
#Override
public void onClick(View view) {
MyViewHolder holder = (MyViewHolder) view.getTag();
Bookings bookingsItem = bookingsList.get(holder.getPosition());
// Check for an expanded view, collapse if you find one
// set previously expanded row to false
for(int i=0;i<bookingsList.size();i++)
{
if(bookingsList.get(i).expanded)
{
bookingsList.get(i).expanded = false;
}
}
//set current item expanded
bookingsList.get(holder.getPosition()).expanded = true;
if (expandedPosition >= 0) {
int prev = expandedPosition;
notifyItemChanged(prev);
}
// Set the current position to "expanded"
expandedPosition = holder.getPosition();
notifyItemChanged(expandedPosition);
Toast.makeText(context, "Clicked: "+ bookingsItem.getEventName(), Toast.LENGTH_SHORT).show();
}
Now I want to close the expanded layout of same item on click of item.
NOTE: Take a boolean variable named expanded in class Bookings and by default save it as false where you are adding values to your list then in your on click do something like this
public class BookingsAdapter extends RecyclerView.Adapter<BookingsAdapter.MyViewHolder> implements View.OnClickListener{
private List<Bookings> bookingsList;
int status;
Context context;
public interface OnItemClickListener {
void onItemClick(Events item);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView eventName,eventType,eventDateTime,userName;
public RelativeLayout expandLayout;
public CardView cardView;
public MyViewHolder(View view) {
super(view);
eventName = (TextView) view.findViewById(R.id.text_eventName);
eventType = (TextView) view.findViewById(R.id.textView_EventType);
eventDateTime = (TextView) view.findViewById(R.id.text_dateTime);
userName = (TextView) view.findViewById(R.id.text_userName);
expandLayout = (RelativeLayout) view.findViewById(R.id.expandLayout);
cardView = (CardView) view.findViewById(R.id.card_view);
}
}
public BookingsAdapter(ArrayList<Bookings> bookingsList,Context context) {
this.bookingsList = bookingsList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.bookings_card, parent, false);
MyViewHolder holder = new MyViewHolder(itemView);
// Sets the click adapter for the entire cell
// to the one in this class.
holder.itemView.setOnClickListener(BookingsAdapter.this);
holder.itemView.setTag(holder);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bookings bookings = bookingsList.get(position);
holder.eventName.setText(bookings.getEventName());
holder.eventType.setText(bookings.getEventType());
holder.eventDateTime.setText(bookings.getEventDateTime());
holder.userName.setText(bookings.getUserName());
if (bookings.expanded) {
holder.expandLayout.setVisibility(View.VISIBLE);
} else {
holder.expandLayout.setVisibility(View.GONE);
}
}
#Override
public void onClick(View view) {
MyViewHolder holder = (MyViewHolder) view.getTag();
if(bookingsList.get(holder.getPosition()).expandad)
{
bookingsList.get(holder.getPosition()).expandad=false;
notifyDataSetChanged();
}
else{
// set previously expanded row to false
for(int i=0;i<bookingsList.size();i++)
{
if(bookingsList.get(i).expanded)
{
bookingsList.get(i).expandad=false;
}
}
//set current item expanded
bookingsList.get(holder.getPosition()).expandad=true;
notifyDataSetChanged();
}
Toast.makeText(context, "Clicked: "+ bookingsItem.getEventName(), Toast.LENGTH_SHORT).show();
}
I know here we have a lot of questions like mine, but I don't know why none works for me.
My objective: I have an AlertDialog with a ListView with a check box in each row, I can select some of the items, and I wish to make an ArrayList with the elements selected.
For that reason, I'm calling the SetOnclickListener, I put a Log inside the method, but does nothing.
I tried with focusable and clickable almost everywhere, but my Log doesn't appear.
Here My alert Dialog
private void callAdditionalDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(ConfigProductActivity.this);
final View additionalView = layoutInflater.inflate(R.layout.dialog_additional, null);
additionalView.setFocusable(true);
// set the custom dialog components - text, buttons, accountants
TextView titleDialog = (TextView) additionalView.findViewById(R.id.title_additional);
titleDialog.setTypeface(boldFont);
Button buttonAccept = (Button) additionalView.findViewById(R.id.button_accept);
buttonAccept.setTypeface(boldFont);
Button buttonCancel = (Button) additionalView.findViewById(R.id.button_cancel);
buttonCancel.setTypeface(boldFont);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ConfigProductActivity.this);
alertDialogBuilder.setView(additionalView);
final AlertDialog alertD = alertDialogBuilder.create();
alertD.setCanceledOnTouchOutside(false);
//Fill object of additional
final ListView additionalListView = (ListView) additionalView.findViewById(R.id.list_additional);
TextView additionalNotFound = (TextView) additionalView.findViewById(R.id.additional_not_found);
if (!withoutModifiers){
additionalAdapter = new AdditionalAdapter(ConfigProductActivity.this, additionalList);
additionalListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
additionalListView.setAdapter(additionalAdapter);
final ArrayList<ModifierEntity> modifierList = new ArrayList<ModifierEntity>();
additionalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Object modifier = additionalListView.getAdapter().getItem(position).toString();
Log.d(TAG, "SOMETHIIIIING");
}
});
}
else{
additionalListView.setVisibility(View.GONE);
additionalNotFound.setVisibility(View.VISIBLE);
additionalNotFound.setTypeface(font);
buttonCancel.setVisibility(View.GONE);
}
//End of fill object of additional
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
buttonAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//additional.setText(additionalAdapter.getCount());
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
alertD.show();
}
Here my adapter:
public class AdditionalAdapter extends ArrayAdapter {
private static String TAG = AdditionalAdapter.class.getName();
private List<ModifierEntity> originalData = null;
private ConfigProductActivity activity;
private Typeface font;
private Typeface boldFont;
private static ModifierEntity modifier;
public AdditionalAdapter (ConfigProductActivity activity, List<ModifierEntity> listArray){
super(activity, R.layout.additional_item);
this.activity = activity;
this.originalData = listArray ;
font = Typeface.createFromAsset(activity.getAssets(),"HelveticaNeueThn.ttf");
boldFont = Typeface.createFromAsset(activity.getAssets(), "avgardm.ttf");
}
public static class Row
{
public TextView labelName;
public TextView labelPrice;
public CheckBox check;
}
#Override
public int getCount() {
return originalData.size();
}
#Override
public ModifierEntity getItem(int position) {
return originalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int colorFont = activity.getResources().getColor(R.color.brown_tataki);
final Row holder;
View rowView = convertView;
// reuse views
if (convertView == null) {
holder = new Row();
LayoutInflater inflater = LayoutInflater.from(activity);
rowView = inflater.inflate(R.layout.additional_item, null);
rowView.setClickable(true);
//rowView.setFocusable(false);
// configure view holder
holder.labelName = (TextView) rowView.findViewById(R.id.additional_name);
holder.labelPrice = (TextView) rowView.findViewById(R.id.additional_price);
holder.check = (CheckBox) rowView.findViewById(R.id.additional_check);
rowView.setTag(holder);
}
else {
holder = (Row) convertView.getTag();
// rowView.setClickable(true);
}
final ModifierEntity itm = originalData.get(position);
holder.labelName.setText(itm.getModifier_name());
holder.labelName.setTypeface(font);
holder.labelName.setTextColor(colorFont);
holder.labelPrice.setText(GlobalParameters.CURRENCY.concat(String.valueOf(itm.getModifier_cost())));
holder.labelPrice.setTypeface(boldFont);
holder.labelPrice.setTextColor(colorFont);
return rowView;
}
}
Here My Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange_tataki"
android:text="#string/additional_title"
android:textColor="#color/white"
android:textSize="20sp"
android:gravity="center"
android:id="#+id/title_additional"
android:padding="5dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title_additional"
android:gravity="center"
android:background="#color/white"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_additional"
android:divider="#color/brown_tataki"
android:dividerHeight="0.5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/list_additional"
android:gravity="center"
android:padding="10dp"
android:visibility="gone"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_not_found"
android:text="#string/additional_not_found"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttons"
android:layout_marginBottom="10dp"
android:layout_below="#+id/additional_not_found"
android:gravity="center"
android:layout_marginTop="20dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/button_cancel"
android:background="#color/green_tataki"
android:text="#string/button_cancel"
android:textSize="15sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_accept"
android:padding="10dp"
android:background="#color/green_tataki"
android:text="#string/button_accept"
android:textSize="15sp"
android:layout_marginLeft="15dp"
/>
</LinearLayout>
</RelativeLayout>
And Here my item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="QUESO"
android:singleLine="true"
android:padding="10dp"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/additional_price"
android:padding="10dp"
android:text="Bs. 500"
android:textColor="#color/brown_tataki"
android:layout_toRightOf="#id/additional_name"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="#+id/additional_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp" />
Using interfaces I can solve my problem, this link provided me the solution, and bassically consist in create an interface and implement in my activity.
Like this:
1.- Interface
public interface MyListener {
void folderClicked();
}
2.- Implements the interface in the activity
public class ActivityA extends Activity implements MyListener
3.- You will have to auto override the method folderClicked it will look like this:
#Override
protected void folderClicked() {
// Do your stuff here.
}
4.- Send the activity listener to the adapter with constructor like this:
MyAdpater adapter = new MyAdpater(ActivityA.this);
5.- Your adapter class your code should be like this:
public class TimeLineAdapter extends BaseAdapter {
private MyListener mListener;
public TimeLineAdapter(MyListener listener) {
super();
mListener = listener;
}
holder.iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onFolderClicked()
//code to do stuff when the image is clicked
}