I create app for sports site and need to make calendar events. There is a detail which I can't understand: how to make headers within Recyclerview for display of tournaments name that not to specified near each game (example "Примера" on the screen).
Is there a library or anyways for my task? I don’t want create many static Recyclerview and find agile ways.
Of course, there are a lot of tournaments in the calendar, so the headers should be the same.
Main class of the calendar:
public class FootballResults extends Fragment implements
View.OnClickListener, DatePickerDialog.OnDateSetListener{
private LinearLayoutManager linLM;
private FootballResultsAdapter adapter;
private ArrayList<FootballResultsData> dl;
String today_day;
String today_month;
String today_year;
String mDay;
String mMonth;
String mYear;
Button arrow_left;
Button arrow_right;
Button datepicker;
Switch swLive;
int n = 0;
//int n_plus = 1;
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rv = inflater.inflate(R.layout.results_football, container, false);
RecyclerView footballresults_feed1 = (RecyclerView) rv.findViewById(R.id.rcMatch1);
dl = new ArrayList<>();
footballresults_feed1.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new FootballResultsAdapter(getActivity(), dl);
footballresults_feed1.setAdapter(adapter);
arrow_left = (Button)rv.findViewById(R.id.arrow_left);
arrow_right = (Button)rv.findViewById(R.id.arrow_right);
datepicker = (Button)rv.findViewById(R.id.btnDatepick);
swLive = (Switch)rv.findViewById(R.id.swLive);
arrow_left.setOnClickListener(this);
arrow_right.setOnClickListener(this);
datepicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datepickermethod ();
}
});
swLive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {swLive.setText("");}
else {swLive.setText("");}
}
});
currenttime();
datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);
ResultDisplay();
return rv;
}
private void ResultDisplay() {
#SuppressLint("StaticFieldLeak") AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
ResultFeed ();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute();
}
void ResultFeed (){
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(C.RESULT_API+mYear+"/"+mMonth+"/"+mDay+"?sport_id=1")
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
JSONObject object = new JSONObject(response.body().string());
dl.clear();
JSONArray sports = object.getJSONArray("sports");
JSONObject tournament0 = sports.getJSONObject(0);
JSONArray tournament = tournament0.getJSONArray("tournaments");
for (int i=0; i<tournament.length(); i++){
JSONObject matches1 = tournament.getJSONObject(i);
Log.i (C.T, "Турнир: "+matches1.getString("tournament_name"));
JSONArray matches0 = matches1.getJSONArray("matches");
for (int j=0; j<matches0.length(); j++) {
JSONObject matches = matches0.getJSONObject(j);
String match_time = TimeFormat.TimeRadar(matches.getString("date_of_match")); //время начала матча
String match_res = matches.getString("ft_value");
String match_status = matches.getString("status");
if (match_res.equals("null")) {match_res = "-:-";}
if (match_status.equals("Не начался")) {match_status = "";}
if (match_status.equals("null")) {match_status = "";}
JSONObject team_home1 = matches.getJSONObject("team_home");
String team_home = team_home1.getString("short_name");
String team_home_logo = team_home1.getString("logo_small");
JSONObject team_away1 = matches.getJSONObject("team_away");
String team_away = team_away1.getString("short_name");
String team_away_logo = team_away1.getString("logo_small");
FootballResultsData data = new FootballResultsData(matches1.getString("tournament_name"),
match_time,
match_res,
team_home, team_away,
match_status,
team_home_logo,
team_away_logo);
dl.add(data);
}}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
#SuppressLint("SimpleDateFormat")
void currenttime () {
long date_today = System.currentTimeMillis();
today_day = new SimpleDateFormat("dd").format(date_today);
today_month = new SimpleDateFormat("MM").format(date_today);
today_year = new SimpleDateFormat("yyyy").format(date_today);
mDay = today_day; mMonth = today_month; mYear = today_year;
}
#SuppressLint("SimpleDateFormat")
void calendar (String dd, String mm, String yyyy, int day_n) {
String sourceDate = yyyy+"-"+mm+"-"+dd;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate;
try {
myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, day_n);
String mDate = new SimpleDateFormat("dd MM yyyy").format(new SimpleDateFormat("EEE MMM dd kk:mm:ss zzzz yyyy").parse(myDate.toString()));
mDay = new SimpleDateFormat("dd").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
mMonth = new SimpleDateFormat("MM").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
mYear = new SimpleDateFormat("yyyy").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
Log.i(C.T, mDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
//currenttime ();
switch (v.getId()) {
case R.id.arrow_left: {n=n-1; break;}
case R.id.arrow_right: {n=n+1; break;}
default: break;
}
calendar(today_day, today_month, today_year, n);
datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);
ResultDisplay();
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
}
void datepickermethod () {
DatePickerDialog datepick = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
datepicker.setText(dayOfMonth+" "+TimeFormat.monthDef(month+1)+" "+year);
mDay = String.valueOf(dayOfMonth); mMonth = String.valueOf(month+1); mYear = String.valueOf(year);
n=0;
today_day = String.valueOf(dayOfMonth); today_month = String.valueOf(month+1); today_year = String.valueOf(year);
ResultDisplay();
}
}, Integer.parseInt(today_year), Integer.parseInt(today_month)-1, Integer.parseInt(today_day));
datepick.show();
}
}
For setters and getters:
class FootballResultsData {
public FootballResultsData(String tournament_name, String match_time, String match_result, String team_home, String team_away, String match_status, String team_home_logo, String team_away_logo) {
this.setTournament_name(tournament_name);
this.setMatch_time(match_time);
this.setMatch_result(match_result);
this.setTeam_home(team_home);
this.setTeam_away(team_away);
this.setMatch_status(match_status);
this.setTeam_home_logo(team_home_logo);
this.setTeam_away_logo(team_away_logo);
}
private String tournament_name;
private String match_time;
private String match_result;
private String team_home;
private String team_away;
private String match_status;
private String team_home_logo;
private String team_away_logo;
public String getMatch_time() { return match_time; }
public void setMatch_time(String match_time) {
this.match_time = match_time;
}
public String getTeam_home() {
return team_home;
}
public void setTeam_home(String team_home) {
this.team_home = team_home;
}
public String getTeam_away() {
return team_away;
}
public void setTeam_away(String team_away) {
this.team_away = team_away;
}
public String getMatch_status() {
return match_status;
}
public void setMatch_status(String match_status) {
this.match_status = match_status;
}
public String getMatch_result() { return match_result; }
public void setMatch_result(String match_result) { this.match_result = match_result; }
public String getTeam_home_logo() {
return team_home_logo;
}
public void setTeam_home_logo(String team_home_logo) {
this.team_home_logo = team_home_logo;
}
public String getTeam_away_logo() {
return team_away_logo;
}
public void setTeam_away_logo(String team_away_logo) {
this.team_away_logo = team_away_logo;
}
public String getTournament_name() {
return tournament_name;
}
public void setTournament_name(String tournament_name) {
this.tournament_name = tournament_name;
}
}
Cardview for a display of match:
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tournament_result" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:background="#drawable/newsbody_file">
<TextView
android:id="#+id/linebelownews"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorNewsPressed" />
<TextView
android:id="#+id/match_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/linebelownews"
android:text="22:00" />
<TextView
android:id="#+id/match_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:text="ост." />
<TextView
android:id="#+id/match_res"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/match_time"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="2:2"
android:textStyle="bold" />
<TextView
android:id="#+id/match_th"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/match_time"
android:layout_marginEnd="5dp"
android:layout_toStartOf="#+id/logo_th"
android:text="Динамо"
android:textAlignment="viewEnd"
android:textColor="#000000" />
<TextView
android:id="#+id/match_ta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_toEndOf="#+id/logo_ta"
android:layout_below="#id/match_time"
android:textColor="#000000"
android:text="Шахтер" />
<ImageView
android:id="#+id/logo_th"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_toStartOf="#id/match_res"
android:layout_below="#+id/match_time"
android:contentDescription="logo_th"
app:srcCompat="#drawable/author_file" />
<ImageView
android:id="#+id/logo_ta"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_below="#id/match_time"
app:srcCompat="#drawable/author_file"
android:layout_toEndOf="#id/match_res"
android:layout_marginBottom="5dp"
android:contentDescription="logo_th" />
<TextView
android:id="#+id/tournament_n"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/match_status"
android:layout_centerHorizontal="true"
android:text="#string/name_tournament" />
</RelativeLayout>
</android.support.v7.widget.CardView>
And main layout with Recyclerview:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tournament_result">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcMatch1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lCalendar">
<Button
android:id="#+id/arrow_left"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_toStartOf="#+id/btnDatepick"
android:background="#drawable/ic_arrow_left" />
<Button
android:id="#+id/arrow_right"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_toEndOf="#+id/btnDatepick"
android:background="#drawable/ic_arrow_right" />
<Button
android:id="#+id/btnDatepick"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Switch
android:id="#+id/swLive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginStart="16dp" />
</RelativeLayout>
</RelativeLayout>
EDIT
Adapter:
class FootballResultsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private ArrayList<FootballResultsData> footballresults_data = new ArrayList<FootballResultsData>();
private static int View_Header = 0;
private static int View_Item = 1;
public FootballResultsAdapter(Context context, ArrayList<FootballResultsData> footballresults_data) {
this.context = context;
this.footballresults_data = footballresults_data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder = null;
if(viewType == View_Item) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_match, parent, false);
holder = new ViewHolder_item(view);
}
else if(viewType == View_Header) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_tournament, parent, false);
holder = new ViewHolder_header(view);
}
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
FootballResultsData NFD = footballresults_data.get(position);
if (holder instanceof ViewHolder_item) {
((ViewHolder_item) holder).match_time.setText(NFD.getMatch_time());
((ViewHolder_item) holder).match_result.setText(NFD.getMatch_result());
((ViewHolder_item) holder).team_home.setText(NFD.getTeam_home());
((ViewHolder_item) holder).team_away.setText(NFD.getTeam_away());
((ViewHolder_item) holder).match_status.setText(NFD.getMatch_status());
Glide.with(context).load(NFD.getTeam_home_logo()).into( ((ViewHolder_item) holder).team_home_logo);
Glide.with(context).load(NFD.getTeam_away_logo()).into( ((ViewHolder_item) holder).team_away_logo);
}
else if (holder instanceof ViewHolder_header) {
((ViewHolder_header) holder).tournament_name.setText(NFD.getTournament_name());
}
}
#Override
public int getItemViewType(int position) {
super.getItemViewType(position);
if(position == 0) {
return View_Header;
}else {
return View_Item;
}
}
#Override
public int getItemCount() {
return footballresults_data.size()+1;
}
public static class ViewHolder_item extends RecyclerView.ViewHolder {
public TextView match_time;
public TextView match_result;
public TextView team_home;
public TextView team_away;
public TextView match_status;
public ImageView team_home_logo;
public ImageView team_away_logo;
public ViewHolder_item(View itemView) {
super(itemView);
match_time = (TextView)itemView.findViewById(R.id.match_time);
match_result = (TextView)itemView.findViewById(R.id.match_res);
team_home = (TextView)itemView.findViewById(R.id.match_th);
team_away = (TextView)itemView.findViewById(R.id.match_ta);
match_status = (TextView)itemView.findViewById(R.id.match_status);
team_home_logo = (ImageView)itemView.findViewById(R.id.logo_th);
team_away_logo = (ImageView)itemView.findViewById(R.id.logo_ta);
}
}
public static class ViewHolder_header extends RecyclerView.ViewHolder {
public TextView tournament_name;
public ViewHolder_header(View itemView) {
super(itemView);
tournament_name = (TextView)itemView.findViewById(R.id.tournament_n);
}
}
}
Override getItemViewType (int position) return the appropriate type based on position and then inflate a different layout for header in onCreateViewHolder.
In Adapter
private static int View_Header =0;
private static int View_Item = 1;
Then
#Override
public int getItemViewType (int position) {
// position 0 return header type
if(position == 0) {
return View_Header;
}else {
return View_Item;
}
}
Then
// add 1 to the list
// total items is item in list + 1 for header
#Override
public int getItemCount() {
return footballresults_data.size()+1;
}
Then
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder = null;
if(viewType == View_Item) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_match, parent, false);
holder = new ViewHolder_Item(view);
}else if(viewType == View_Header) {
// inflate header layout
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.header_layout, parent, false);
holder = new ViewHolder_header(view);
}
return holder;
}
Then
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolder) {
// bind row items items
}
// create a separate viewholder class for header
else if( holder instanceof ViewHolder_header){
// bind header item
}
If you are looking for header and sub items (grouping items under a header) have a look at https://stackoverflow.com/a/42976078/653856. But the logic remains the same
Related
I want to ask you, how to change programmatically the background color of LinearLayout in CardView when the text in TextView equals specify word or is empty. For example field1 getting string "red", the background of LinearLayout gets red. I'm fetching the data from JSON php file.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private String jsonURL = "http://example.com/test.php";
private final int jsoncode = 1;
private RecyclerView recyclerView;
ArrayList<Model> ModelArrayList;
private Adapter adapter;
private static ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
fetchJSON();
}
#SuppressLint("StaticFieldLeak")
private void fetchJSON(){
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
HashMap<String, String> map=new HashMap<>();
try {
HttpRequest req = new HttpRequest(jsonURL);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
onTaskCompleted(result,jsoncode);
}
}.execute();
}
public void onTaskCompleted(String response, int serviceCode) {
Log.d("responsejson", response.toString());
switch (serviceCode) {
case jsoncode:
if (isSuccess(response)) {
removeSimpleProgressDialog(); //will remove progress dialog
ModelArrayList = getInfo(response);
adapter = new Adapter(this,ModelArrayList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}else {
Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
}
}
}
public ArrayList<Model> getInfo(String response) {
ArrayList<Model> ModelArrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("true")) {
JSONArray dataArray = jsonObject.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
Model fieldsModel = new Model();
JSONObject dataobj = dataArray.getJSONObject(i);
fieldsModel.setField1(dataobj.getString("field1"));
fieldsModel.setField2(dataobj.getString("field2"));
ModelArrayList.add(fieldsModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return ModelArrayList;
}
public boolean isSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.optString("status").equals("true")) {
return true;
} else {
return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
public String getErrorCode(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
return "No data";
}
}
Adapter.class
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private LayoutInflater inflater;
private ArrayList<Model> ModelArrayList;
public Adapter(Context ctx, ArrayList<Model> rogerModelArrayList){
inflater = LayoutInflater.from(ctx);
this.ModelArrayList = rogerModelArrayList;
}
#Override
public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
holder.field1.setText(ModelArrayList.get(position).getField1());
holder.field2.setText(ModelArrayList.get(position).getField2());
}
#Override
public int getItemCount() {
return ModelArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView field1,field2;
public MyViewHolder(View itemView) {
super(itemView);
field1 = (TextView) itemView.findViewById(R.id.field1);
field2 = (TextView) itemView.findViewById(R.id.field2);
}
}
}
Model.class
public class Model {
private String field1, field2;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#cd15e6"
tools:context=".MainActivity">
** <android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="15dp"/> **
</LinearLayout>
rv_item.xml
Here is the LinearLayout which i want to change the color LL_background
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/LL_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/field1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:text="ddd"
android:textColor="#000"
android:textStyle="bold" />
<TextView
android:id="#+id/field2"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="ddd"
android:textColor="#000"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Please check my project and share your ideas. Thanks a lot 😊
First of all add layout reference to ViewHolder
class MyViewHolder extends RecyclerView.ViewHolder{
TextView field1,field2;
LinearLayout layout;
public MyViewHolder(View itemView) {
super(itemView);
field1 = (TextView) itemView.findViewById(R.id.field1);
field2 = (TextView) itemView.findViewById(R.id.field2);
layout = itemView.findViewById(R.id.LL_background);
}
}
Then check Field1 and set color
#Override
public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
holder.field1.setText(ModelArrayList.get(position).getField1());
holder.field2.setText(ModelArrayList.get(position).getField2());
if(ModelArrayList.get(position).getField1().equalIgnoreCase("red")
holder.layout.setBackgroundColor(Color.RED)
}
red is not recognizable in android. Either you have to handle it manually like above or you can send the corresponding #code of color from server and handle it like below:
holder.layout.setBackgroundColor(Color.parseColor("#ff0000"));
You can change layout instead color. Create different layouts that has different background color or different design. Then do this.
#Override
public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
if(ModelArrayList.get(position).getField1().equalIgnoreCase("red")
view = inflater.inflate(R.layout.anotherLayout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
I have 2 Adapter classes with their Object class also:
First Adapter class is:
public class UpcomingAdpter extends RecyclerView.Adapter<UpcomingAdpter.ItemRowHolder> {
private ArrayList<UpcomingObject> itemList;
private Context context;
public UpcomingAdpter(ArrayList<UpcomingObject> itemList, Context context){
this.itemList = itemList;
this.context = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.upcominglayout, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String sectionName = itemList.get(i).getDate();
final ArrayList<SingleItemModelForUpcoming> singleSectionItems = itemList.get(i).getNamesList();
final ArrayList<SingleItemforPhoneNumbers> singleSectionItemsForPhoneNumber = itemList.get(i).getPhoneList();
itemRowHolder.date.setText(sectionName);
AdapterForNamesListInUpcoming itemListDataAdapter = new AdapterForNamesListInUpcoming(context, singleSectionItemsForPhoneNumber, singleSectionItems);
AdapterForNamesListInUpcoming itemListDataAdapterSecond = new AdapterForNamesListInUpcoming(context, singleSectionItemsForPhoneNumber, singleSectionItems);
itemRowHolder.recycler_view_list.setHasFixedSize(true);
itemRowHolder.recycler_view_list.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapterSecond);
itemRowHolder.recycler_view_list.setNestedScrollingEnabled(false);
itemRowHolder.recycler_view_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("dd","here is me");
}
});
}
#Override
public int getItemCount() {
return (null != itemList ? itemList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView date;
protected RecyclerView recycler_view_list;
public ItemRowHolder(View view) {
super(view);
this.date = (TextView) view.findViewById(R.id.date);
this.recycler_view_list = (RecyclerView) view.findViewById(R.id.recycler_view_list);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String finaldate = date.getText().toString();
Log.d("Date", "now date us "+finaldate);
}
}
}
The Object Class for this is :
public class UpcomingObject {
private String Date;
private ArrayList<SingleItemModelForUpcoming> NamesList;
private ArrayList<SingleItemforPhoneNumbers> PhoneList;
public UpcomingObject() {
}
public UpcomingObject(String Date, ArrayList<SingleItemModelForUpcoming> NamesList, ArrayList<SingleItemforPhoneNumbers> PhoneList) {
this.Date = Date;
this.NamesList = NamesList;
this.PhoneList = PhoneList;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public ArrayList<SingleItemModelForUpcoming> getNamesList() {
return NamesList;
}
public void setNamesList(ArrayList<SingleItemModelForUpcoming> namesList) {
NamesList = namesList;
}
public ArrayList<SingleItemforPhoneNumbers> getPhoneList() {
return PhoneList;
}
public void setPhoneList(ArrayList<SingleItemforPhoneNumbers> phoneList) {
PhoneList = phoneList;
}
}
The Layout for this is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginLeft="50dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="#+id/date"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="#font/gothic"
android:layout_marginTop="10dp"
android:textColor="#000"
android:text="10-10-2019"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_marginTop="40dp"
android:id="#+id/takedate"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginTop="5dp"
android:layout_marginLeft="20dp"
android:orientation="vertical" />
</RelativeLayout>
The Second Adapter class is :
public class AdapterForNamesListInUpcoming extends RecyclerView.Adapter<AdapterForNamesListInUpcoming.SingleItemRowHolder> {
private List<SingleItemModelForUpcoming> itemsList;
private List<SingleItemforPhoneNumbers> itemforPhoneNumbers;
private Context mContext;
public AdapterForNamesListInUpcoming(Context context, List<SingleItemforPhoneNumbers> itemforPhoneNumbers , List<SingleItemModelForUpcoming> itemsList ) {
this.itemsList = itemsList;
this.itemforPhoneNumbers = itemforPhoneNumbers;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.upcomingclientlistlayout, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModelForUpcoming singleItem = itemsList.get(i);
SingleItemforPhoneNumbers singleItemforPhoneNumbers = itemforPhoneNumbers.get(i);
holder.nameofclient.setText(singleItem.getName());
holder.phoneNumber.setText(singleItemforPhoneNumbers.getPhoneNumber());
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView nameofclient , phoneNumber, date;
public SingleItemRowHolder(View view) {
super(view);
this.nameofclient = (TextView) view.findViewById(R.id.nameofclient);
this.phoneNumber = (TextView)view.findViewById(R.id.phoneNumber);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent UpcomingDetailPage = new Intent(v.getContext(), com.allwaseet.spaservshop.UpcomingDetailsPage.UpcomingDetailPage.class);
v.getContext().startActivity(UpcomingDetailPage);
String finalPhoneNumber = phoneNumber.getText().toString();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
SharedPreferences.Editor PhoneNumberEditor;
SharedPreferences PhoneNumberSharedPreference;
PhoneNumberSharedPreference = mContext.getSharedPreferences("SelectedPhoneNumber", Context.MODE_PRIVATE);
PhoneNumberEditor = PhoneNumberSharedPreference.edit();
PhoneNumberEditor.putString("SelectedPhoneNumber",finalPhoneNumber);
PhoneNumberEditor.commit();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.upcominglayout, null, true);
TextView textView = (TextView)view.findViewById( R.id.date );
String finaldate = textView.getText().toString();
Log.d("ss","date is "+finaldate);
SharedPreferences.Editor DateEditor;
SharedPreferences DateSharedPreference;
DateSharedPreference = mContext.getSharedPreferences("DateInUpcoming", Context.MODE_PRIVATE);
DateEditor = DateSharedPreference.edit();
DateEditor.putString("DateInUpcoming",finaldate);
DateEditor.commit();
// return view;
}
}
}
Object class for this is :
public class SingleItemModelForUpcoming {
private String name;
public SingleItemModelForUpcoming(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Layout for this is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="550dp"
android:layout_marginTop="40dp"
android:layout_height="150dp"
android:layout_marginLeft="50dp"
android:paddingBottom="30dp"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="560dp"
android:background="#drawable/upcomingandhistorybackground"
android:layout_height="100dp">
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:text="2:30"
android:layout_marginTop="35dp"
android:textSize="25dp"
android:fontFamily="#font/gothic"
android:layout_marginLeft="20dp"
android:textColor="#fff"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"
android:layout_height="70dp"
android:background="#fff"
/>
<TextView
android:id="#+id/nameofclient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:layout_marginLeft="100dp"
android:layout_marginTop="35dp"
android:textColor="#fff"
android:fontFamily="#font/gothic"
android:textSize="20dp"/>
<!--Not in use-->
<TextView
android:id="#+id/phoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_marginLeft="100dp"
android:layout_marginTop="4dp"
android:textColor="#fff"
android:text="rr"
android:fontFamily="#font/gothic"
android:textSize="20dp"/>
<!--Not in use-->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginLeft="495dp"
android:src="#drawable/rightarrow"/>
Now what I want is when I click the item which is present in the Second Adapter class, I want to take the date which is specified in the first adapter class. How can I do this.
This is the example picture
For example:
when I click on the pink portion or cell I should get the date also with it. But the problem is the date is specified in another adapter class
Any help would be appreciated.
use this
public class AdapterForNamesListInUpcoming extends RecyclerView.Adapter<AdapterForNamesListInUpcoming.SingleItemRowHolder> {
private List<SingleItemModelForUpcoming> itemsList;
private List<SingleItemforPhoneNumbers> itemforPhoneNumbers;
private ArrayList<UpcomingObject> item;
private Context mContext;
public AdapterForNamesListInUpcoming(Context context,ArrayList<UpcomingObject> item, List<SingleItemforPhoneNumbers> itemforPhoneNumbers , List<SingleItemModelForUpcoming> itemsList ) {
this.itemsList = itemsList;
this.item = item;
this.itemforPhoneNumbers = itemforPhoneNumbers;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.upcomingclientlistlayout, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModelForUpcoming singleItem = itemsList.get(i);
SingleItemforPhoneNumbers singleItemforPhoneNumbers = itemforPhoneNumbers.get(i);
holder.nameofclient.setText(singleItem.getName());
holder.phoneNumber.setText(singleItemforPhoneNumbers.getPhoneNumber());
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView nameofclient , phoneNumber, date;
public SingleItemRowHolder(View view) {
super(view);
this.nameofclient = (TextView) view.findViewById(R.id.nameofclient);
this.phoneNumber = (TextView)view.findViewById(R.id.phoneNumber);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpcomingObject up = item.get(getAdapterPosition);
Intent UpcomingDetailPage = new Intent(v.getContext(), com.allwaseet.spaservshop.UpcomingDetailsPage.UpcomingDetailPage.class);
v.getContext().startActivity(UpcomingDetailPage);
String finalPhoneNumber = phoneNumber.getText().toString();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
SharedPreferences.Editor PhoneNumberEditor;
SharedPreferences PhoneNumberSharedPreference;
PhoneNumberSharedPreference = mContext.getSharedPreferences("SelectedPhoneNumber", Context.MODE_PRIVATE);
PhoneNumberEditor = PhoneNumberSharedPreference.edit();
PhoneNumberEditor.putString("SelectedPhoneNumber",finalPhoneNumber);
PhoneNumberEditor.commit();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.upcominglayout, null, true);
TextView textView = (TextView)view.findViewById( R.id.date );
String finaldate = textView.getText().toString();
Log.d("ss","date is "+finaldate);
SharedPreferences.Editor DateEditor;
SharedPreferences DateSharedPreference;
DateSharedPreference = mContext.getSharedPreferences("DateInUpcoming", Context.MODE_PRIVATE);
DateEditor = DateSharedPreference.edit();
DateEditor.putString("DateInUpcoming",finaldate);
DateEditor.commit();
// return view;
}
});
}
}
}
You can pass data from one class to another class on click event of button or any item using Intent so you can do is that store your data of 1st class into Shared preference and then pass data in form of key value pair like this:
public class AdapterForNamesListInUpcoming extends
RecyclerView.Adapter<AdapterForNamesListInUpcoming.SingleItemRowHolder> {
private List<SingleItemModelForUpcoming> itemsList;
private List<SingleItemforPhoneNumbers> itemforPhoneNumbers;
private ArrayList<UpcomingObject> item;
private Context ctx;
public AdapterForNamesListInUpcoming(Context
context,ArrayList<UpcomingObject> item, List<SingleItemforPhoneNumbers>
itemforPhoneNumbers , List<SingleItemModelForUpcoming> itemsList ) {
this.itemsList = itemsList;
this.item = item;
this.itemforPhoneNumbers = itemforPhoneNumbers;
this.ctx = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v =
LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.upcomingclientlistlayout, null);
SingleItemRowHolder rh = new SingleItemRowHolder(v);
return rh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModelForUpcoming singleItem = itemsList.get(i);
SingleItemforPhoneNumbers singleItemforPhoneNumbers =
itemforPhoneNumbers.get(i);
holder.nameofclient.setText(singleItem.getName());
holder.phoneNumber.setText(singleItemforPhoneNumbers.getPhoneNumber());
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
protected TextView nameofclient , phoneNumber, date;
public SingleItemRowHolder(View view) {
super(view);
this.nameofclient = (TextView) view.findViewById(R.id.nameofclient);
this.phoneNumber = (TextView)view.findViewById(R.id.phoneNumber);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// get data of first adapter
UpcomingObject up = item.get(getAdapterPosition);
Intent UpcomingDetailPage = new Intent(v.getContext(),
com.allwaseet.spaservshop.UpcomingDetailsPage.UpcomingDetailPage.class);
v.getContext().startActivity(UpcomingDetailPage);
String finalPhoneNumber = phoneNumber.getText().toString();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
SharedPreferences.Editor PhoneNumberEditor;
SharedPreferences PhoneNumberSharedPreference;
PhoneNumberSharedPreference =
ctx.getSharedPreferences("SelectedPhoneNumber", Context.MODE_PRIVATE);
PhoneNumberEditor = PhoneNumberSharedPreference.edit();
PhoneNumberEditor.putString("SelectedPhoneNumber",finalPhoneNumber);
PhoneNumberEditor.commit();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
LayoutInflater inflater = LayoutInflater.from(ctx);
View view = inflater.inflate(R.layout.upcominglayout, null, true);
TextView textView = (TextView)view.findViewById( R.id.date );
String finaldate = textView.getText().toString();
Log.d("ss","date is "+finaldate);
SharedPreferences.Editor DateEditor;
SharedPreferences DateSharedPreference;
DateSharedPreference = ctx.getSharedPreferences("DateInUpcoming",
Context.MODE_PRIVATE);
DateEditor = DateSharedPreference.edit();
DateEditor.putString("DateInUpcoming",finaldate);
DateEditor.commit();
// return view;
}
}
}
I'm parsing a JSON into a ExpandableListView, on each child the user can select the amount of each child he wants to have due +/- Buttons. The +/- Buttons are connected to a TextView where the total amount of each child gets displayed and the total cost will be displayed at the end of the line.
At the Bottom of the parent there should be a TextView with the summary of all the values calculated in every child of the ExpListView (Summary)
And the OK Button at the Bottom should send the amount of each child to the server (the amount is connected to a ID).
I'm having problems with reading out the amount of each child when I'm clicking on the "OK" Button - how can I build the bridge to the values of my Childs?
I also encounter problems reading out the cost of each childto calculate the total cost at the bottom. The onClickListener in the Child should somehow refresh the TextView at the bottom, but as far as I know, that's not going to be easy, right?
Has anyone an idea how to access the values?
This is the ChildView of my ListAdapter where the magic happens:
public class ExpandableListAdapterDrinks extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader,listDataHeaderPrice;
private HashMap<String,List<String>> listHashMap;
private List<Drink> drinksList;
class ViewHolder {
TextView childText,counterText, childUnitPrice, childFinalPrice;
Button btn_plus,btn_minus;
}
class DrinksListChildItem{
String name;
int quantity;
DrinksListChildItem(String name, int quantity){
this.name = name;
this.quantity = quantity;
}
}
class Pos{
int group;
int child;
Pos(int group, int child){
this.group = group;
this.child = child;
}
}
public ExpandableListAdapterDrinks(Context context, List<Drink> drinksList) {
this.context = context;
this.drinksList= drinksList;
}
#Override
public int getGroupCount() {
return drinksList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return drinksList.get(groupPosition).getContent().size();
}
#Override
public Object getGroup(int groupPosition) {
return drinksList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return drinksList.get(groupPosition).getContent();
listHashMap.get(listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View view, ViewGroup parent) {
String headerTitle = (String) drinksList.get(groupPosition).getTitle();
/** HEADER TEXT HERE */
if(view==null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_package_listgroup,null);
}
final LinearLayout bgcolor = view.findViewById(R.id.lblListHeaderLayout);
TextView lblListHeader = (TextView)view.findViewById(R.id.lblListHeader);
TextView lblListHeaderPrice = (TextView)view.findViewById(R.id.lblListHeader_Price);
Button lblListHeaderButton = view.findViewById(R.id.lblListHeaderButton);
lblListHeaderPrice.setVisibility(View.GONE);
lblListHeaderButton.setVisibility(View.GONE);
if(!drinksList.get(groupPosition).getBg().get(0).isEmpty() || !drinksList.get(groupPosition).getBg().get(1).isEmpty() ) {
List<String> colorGradientTopBottom = drinksList.get(groupPosition).getBg();
int[] colors = {Color.parseColor(colorGradientTopBottom.get(0)),Color.parseColor(colorGradientTopBottom.get(1))};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
gd.setCornerRadius(0f);
bgcolor.setBackground(gd);
} else {
bgcolor.setBackgroundColor(ContextCompat.getColor(context, R.color.cardview_bg));
}
lblListHeader.setText(headerTitle);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
/** Drinks List */
final ViewHolder viewHolder;
final List<String> childDrink = drinksList.get(groupPosition).getContent();
final List<Integer> childPrice = drinksList.get(groupPosition).getPricelist();
//final String childText = childDrink.get(childPosition);
if(view == null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_drinks_listitem,null);
final TextView txtListChild = view.findViewById(R.id.lblListItemDrinks);
final TextView txtListDrinksUnitPrice = view.findViewById(R.id.lblListItemDrinksUnitPrice);
final TextView txtDrinksAmount = view.findViewById(R.id.vip_drinks_amount);
final TextView txtListDrinkPriceFinal = view.findViewById(R.id.lblListItemDrinksFinalPrice);
Button btn_plus = view.findViewById(R.id.vip_drinks_btn_plus);
Button btn_minus = view.findViewById(R.id.vip_drinks_btn_minus);
viewHolder = new ViewHolder();
viewHolder.childText = txtListChild;
viewHolder.childUnitPrice = txtListDrinksUnitPrice;
viewHolder.counterText = txtDrinksAmount;
viewHolder.childFinalPrice = txtListDrinkPriceFinal;
viewHolder.btn_plus = btn_plus;
viewHolder.btn_minus = btn_minus;
viewHolder.childText.setText(childDrink.get(childPosition));
viewHolder.counterText.setText("0");
viewHolder.childFinalPrice.setText("0");
final float headerPrice = childPrice.get(childPosition);
final int headerPriceInt = (int) headerPrice;
viewHolder.childUnitPrice.setText(String.format("%.02f",headerPrice).replace(".",",") +"€");
DrinksListChildItem child = childDrink.get(childPosition);
viewHolder.btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int t = Integer.parseInt(viewHolder.counterText.getText().toString());
ChildItem selectedItem = viewHolder.counterText.getText().toString();
selectedItem.quantity = selectedItem.quantity+1;
notifyDataSetChanged();
viewHolder.counterText.setText(String.valueOf(t + 1));
viewHolder.childFinalPrice.setText(String.valueOf((t+1)* headerPriceInt) + "€");
}
});
viewHolder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int t = Integer.parseInt(viewHolder.counterText.getText().toString());
DrinksListChildItem selectedItem = (DrinksListChildItem) getChild(pos.group,pos.child);
selectedItem.quantity = selectedItem.quantity-1;
notifyDataSetChanged();
viewHolder.counterText.setText(String.valueOf(t - 1));
viewHolder.counterText.setText(String.valueOf((t-1)* headerPriceInt) + "€");
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
return view;
I'm having massive problems glueing your code to my Code (expand problem with a TextView): I don't understand exactly how to connect the ChildItem child = childDrink.get(childPosition); to my drinksList to make the setOnCLickListener increase the selectedItem.quantity. The Code works somehow, but it messes up the order of my childs and it also selects the quantity in the other childs
Drinks (Pojo)
public class Drink {
#SerializedName("title")
#Expose
private String title;
#SerializedName("bg")
#Expose
private List<String> bg = null;
#SerializedName("content")
#Expose
private List<String> content = null;
#SerializedName("pricelist")
#Expose
private List<Integer> pricelist = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getBg() {
return bg;
}
public void setBg(List<String> bg) {
this.bg = bg;
}
public List<String> getContent() {
return content;
}
public void setContent(List<String> content) {
this.content = content;
}
public List<Integer> getPricelist() {
return pricelist;
}
public void setPricelist(List<Integer> pricelist) {
this.pricelist = pricelist;
}
}
VipDrinks(Pojo):
public class VipDrinks {
#SerializedName("drinks")
#Expose
private List<Drink> drinks = null;
public List<Drink> getDrinks() {
return drinks;
}
public void setDrinks(List<Drink> drinks) {
this.drinks = drinks;
}
}
JSON has the following structure:
{
"drinks":[ {
"title":,
"bg":[],
"content":[],
"pricelist":[],
},
{...}
]
}
Here is the Activity with the Parsing Request:
public class drinks_selection extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drinks_selection);
final ExpandableListView listView = findViewById(R.id.vip_drinks_listview);
/** PARSING JSON FROM SERVER */
final JsonObjectRequest galleryUrls = new JsonObjectRequest(Request.Method.GET, PARSE_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray packageArray = response.getJSONArray("drinks");
Log.e("response", String.valueOf(response));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Drink> vipDrinks = Arrays.asList(gson.fromJson(String.valueOf(packageArray),Drink[].class));
List<Drink> arrayList = new ArrayList<>(vipDrinks);
ExpandableListAdapterDrinks listAdapter = new ExpandableListAdapterDrinks(getApplicationContext(),arrayList);
listView.setAdapter( listAdapter);
listView.expandGroup(0);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", String.valueOf(error));
}
});
RequestQueue rQ = Volley.newRequestQueue(this);
rQ.add(galleryUrls);
}
}
VIP Package List Group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/lblListHeaderLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/default_padding"
android:background="#drawable/bg_vip_booking"
android:orientation="horizontal"
>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingStart="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingEnd="#dimen/feed_item_padding_left_right"
android:layout_weight="0.9"
>
<TextView
android:id="#+id/lblListHeader"
android:textSize="#dimen/text_title_list_header"
android:textColor="#color/Textwhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_bold"
/>
<TextView
android:id="#+id/lblListHeader_Price"
android:textSize="#dimen/text_title_list_header"
android:textColor="#color/Textwhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:fontFamily="#font/mont_bold"
/>
</RelativeLayout>
<Button
android:id="#+id/lblListHeaderButton"
android:layout_width="60dp"
android:layout_height="30dp"
android:background="#drawable/bg_btn_ripple_dark"
android:text="#string/btn_ok"
android:textColor="#color/Textwhite"
android:fontFamily="#font/mont_bold"
android:focusable="false"
/>
</LinearLayout>
VIP Drinks ListItem.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dip"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_centerInParent="true"
>
<TextView
android:id="#+id/lblListItemDrinks"
android:paddingTop="#dimen/padding_small"
android:paddingBottom="#dimen/padding_small"
android:textSize="#dimen/text_normal"
android:paddingLeft="#dimen/default_padding"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_medium"
android:textColor="#color/Textwhite"
app:layout_constraintStart_toStartOf="parent"
/>
<RelativeLayout
android:id="#+id/vip_drinks_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/lblListItemDrinks"
android:paddingStart="#dimen/default_padding"
android:layout_centerInParent="true"
android:paddingEnd="#dimen/default_padding"
app:layout_constraintEnd_toEndOf="parent"
>
<TextView
android:id="#+id/lblListItemDrinksUnitPrice"
android:textSize="#dimen/text_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_light"
android:textColor="#color/Textwhite"
android:paddingEnd="#dimen/padding_small"
/>
<Button
android:id="#+id/vip_drinks_btn_minus"
android:layout_toEndOf="#id/lblListItemDrinksUnitPrice"
android:layout_width="30dp"
android:layout_height="20dp"
android:text="-"
android:background="#drawable/bg_btn_ripple_dark"
android:textColor="#color/white"
android:textSize="14sp"
android:layout_marginEnd="#dimen/padding_small"
/>
<TextView
android:id="#+id/vip_drinks_amount"
android:layout_toEndOf="#+id/vip_drinks_btn_minus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:fontFamily="#font/mont_light"
android:textSize="#dimen/text_normal"
android:layout_marginEnd="#dimen/padding_small"
/>
<Button
android:id="#+id/vip_drinks_btn_plus"
android:layout_toEndOf="#+id/vip_drinks_amount"
android:layout_width="30dp"
android:layout_height="20dp"
android:text="+"
android:background="#drawable/bg_btn_ripple_dark"
android:textColor="#color/white"
android:textSize="14sp"
android:layout_marginEnd="#dimen/padding_small"
/>
<TextView
android:id="#+id/lblListItemDrinksFinalPrice"
android:layout_toEndOf="#id/vip_drinks_btn_plus"
android:textSize="#dimen/text_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_light"
android:textColor="#color/Textwhite"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Add a new class SelectedDrink like this:
public class SelectedDrink {
String content;
int qty;
}
Then try this adapter code:
public class ExpandableListAdapterDrinks extends BaseExpandableListAdapter {
private Context context;
private List<Drink> drinksList;
private Button btReset, btOk;
private List<Integer> groupSum;
private List<List<Integer>> qty;
private int totalSum = 0;
class ViewHolder {
TextView childText,counterText, childUnitPrice, childFinalPrice;
Button btn_plus,btn_minus;
}
class Pos{
int group;
int child;
Pos(int group, int child){
this.group = group;
this.child = child;
}
}
public ExpandableListAdapterDrinks(Context context, List<Drink> drinksList,
Button btReset, Button btOk) {
this.context = context;
this.drinksList= drinksList;
this.btReset = btReset;
this.btOk = btOk;
groupSum = new ArrayList<>();
qty = new ArrayList<>();
for(int i=0; i<drinksList.size(); i++) {
groupSum.add(0);
List<Integer> orderedQty = new ArrayList<>();
for(int j=0; j<drinksList.get(i).getContent().size(); j++) orderedQty.add(0);
qty.add(orderedQty);
}
}
private void resetGroupSum(int groupPosition) {
totalSum -= groupSum.get(groupPosition);
groupSum.set(groupPosition, 0);
resetGroupChildrenQty(groupPosition);
}
private void resetGroupChildrenQty(int groupPosition) {
for(int i=0; i<qty.get(groupPosition).size(); i++) qty.get(groupPosition).set(i, 0);
}
#Override
public int getGroupCount() {
return drinksList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return drinksList.get(groupPosition).getContent().size();
}
#Override
public Drink getGroup(int groupPosition) {
return drinksList.get(groupPosition);
}
#Override
public String getChild(int groupPosition, int childPosition) {
return drinksList.get(groupPosition).getContent().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {
String headerTitle = drinksList.get(groupPosition).getTitle();
/** HEADER TEXT HERE */
if(view==null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_package_listgroup,null);
}
LinearLayout bgcolor = view.findViewById(R.id.lblListHeaderLayout);
TextView lblListHeader = (TextView)view.findViewById(R.id.lblListHeader);
TextView lblListHeaderPrice = (TextView)view.findViewById(R.id.lblListHeader_Price);
Button lblListHeaderButton = view.findViewById(R.id.lblListHeaderButton);
if(groupSum.get(groupPosition) > 0){
lblListHeaderPrice.setVisibility(View.VISIBLE);
lblListHeaderPrice.setText(String.format("%.02f", (float)groupSum.get(groupPosition)).replace(".", ",") + "€");
}else{
lblListHeaderPrice.setVisibility(View.GONE);
lblListHeaderButton.setVisibility(View.GONE);
}
if(!drinksList.get(groupPosition).getBg().get(0).isEmpty() || !drinksList.get(groupPosition).getBg().get(1).isEmpty() ) {
List<String> colorGradientTopBottom = drinksList.get(groupPosition).getBg();
int[] colors = {Color.parseColor(colorGradientTopBottom.get(0)),Color.parseColor(colorGradientTopBottom.get(1))};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
gd.setCornerRadius(0f);
bgcolor.setBackground(gd);
} else {
//bgcolor.setBackgroundColor(ContextCompat.getColor(context, R.color.cardview_bg));
}
lblListHeader.setText(headerTitle);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
/** Drinks List */
ViewHolder viewHolder;
String childDrink = getChild(groupPosition, childPosition);
int childPrice = getGroup(groupPosition).getPricelist().get(childPosition);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_drinks_listitem, null);
viewHolder = new ViewHolder();
viewHolder.childText = view.findViewById(R.id.lblListItemDrinks);
viewHolder.childUnitPrice = view.findViewById(R.id.lblListItemDrinksUnitPrice);
viewHolder.counterText = view.findViewById(R.id.vip_drinks_amount);
viewHolder.childFinalPrice = view.findViewById(R.id.lblListItemDrinksFinalPrice);
viewHolder.btn_plus = view.findViewById(R.id.vip_drinks_btn_plus);
viewHolder.btn_minus = view.findViewById(R.id.vip_drinks_btn_minus);
viewHolder.btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int orderedQty = qty.get(pos.group).get(pos.child);
orderedQty++;
qty.get((pos.group)).set(pos.child, orderedQty);
groupSum.set(pos.group, groupSum.get(pos.group) + getGroup(pos.group).getPricelist().get(pos.child));
notifyDataSetChanged();
totalSum += getGroup(pos.group).getPricelist().get(pos.child);
btOk.setText(String.format("%.02f", (float)totalSum).replace(".", ",") + "€");
btReset.setEnabled(true);
}
});
viewHolder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int orderedQty = qty.get(pos.group).get(pos.child);
if (orderedQty > 0) {
orderedQty--;
qty.get((pos.group)).set(pos.child, orderedQty);
groupSum.set(pos.group, groupSum.get(pos.group) - getGroup(pos.group).getPricelist().get(pos.child));
notifyDataSetChanged();
totalSum -= getGroup(pos.group).getPricelist().get(pos.child);
if (totalSum == 0) resetTotalSum();
else btOk.setText(String.format("%.02f", (float)totalSum).replace(".", ",") + "€");
}
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.childText.setText(childDrink);
viewHolder.childUnitPrice.setText(String.format("%.02f", (float)childPrice).replace(".", ",") + "€");
int orderedQty = qty.get(groupPosition).get(childPosition);
viewHolder.counterText.setText(String.valueOf(orderedQty));
viewHolder.childFinalPrice.setText(String.format("%.02f", (float)orderedQty*childPrice).replace(".", ",") + "€");
viewHolder.btn_minus.setTag(new Pos(groupPosition, childPosition));
viewHolder.btn_plus.setTag(new Pos(groupPosition, childPosition));
view.setTag(viewHolder);
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return false;
}
public void resetTotalSum() {
for(int i=0; i<drinksList.size(); i++) {
resetGroupSum(i);
}
notifyDataSetChanged();
btReset.setEnabled(false);
btOk.setText(String.valueOf(0));
}
public ArrayList<SelectedDrink> getOrderList() {
ArrayList<SelectedDrink> orderList = new ArrayList<>();
for(int i=0; i<drinksList.size(); i++) {
for(int j=0; j<drinksList.get(i).getContent().size(); j++) {
if(qty.get(i).get(j) > 0) {
SelectedDrink selectedDrink = new SelectedDrink();
selectedDrink.content = getGroup(i).getContent().get(j);
selectedDrink.qty = qty.get(i).get(j);
orderList.add(selectedDrink);
}
}
}
return orderList;
}
}
I test the above with this activity:
public class MainActivity extends AppCompatActivity {
final private static int NUM_OF_GROUP = 5;
List<Drink> drinksList;
ExpandableListView listView;
ExpandableListAdapterDrinks expandableListAdapterDrinks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btRest = findViewById(R.id.btReset);
Button btOk = findViewById(R.id.btOK);
listView = findViewById(R.id.elvDrinks);
initDataList();
expandableListAdapterDrinks =
new ExpandableListAdapterDrinks(getApplicationContext(), drinksList, btRest, btOk);
listView.setAdapter(expandableListAdapterDrinks);
listView.expandGroup(0);
btRest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expandableListAdapterDrinks.resetTotalSum();
for(int i=0; i<drinksList.size(); i++) listView.collapseGroup(i);
listView.expandGroup(0);
}
});
btOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = "Nothing Selected";
Button button = (Button)view;
if(!button.getText().equals("0")) {
msg = "Upload!\n";
ArrayList<SelectedDrink> selectedDrinks = expandableListAdapterDrinks.getOrderList();
for(SelectedDrink selectedDrink: selectedDrinks) {
msg += selectedDrink.content + " " + selectedDrink.qty + "\n";
}
msg += "Total: " + button.getText();
}
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initDataList(){
drinksList = new ArrayList<>();
List<String> content;
List<Integer> pricelist;
List<String> bg;
for(int i=1; i<=NUM_OF_GROUP; i++) {
content = new ArrayList<>();
pricelist = new ArrayList<>();
bg = new ArrayList<>();
for(int j = 1; j<(NUM_OF_GROUP + new Random().nextInt(5)); j++){
content.add("Drink " + i + "-" + j);
pricelist.add(new Random().nextInt(1000));
bg.add("#008577");
bg.add("#D81B60");
}
Drink drink = new Drink();
drink.setTitle("Group " + i);
drink.setContent(content);
drink.setPricelist(pricelist);
drink.setBg(bg);
drinksList.add(drink);
}
}
}
and this layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/llBtns"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="#+id/btReset"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:text="Reset" />
<Button
android:id="#+id/btOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="0" />
</LinearLayout>
<ExpandableListView
android:id="#+id/elvDrinks"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/llBtns">
</ExpandableListView>
</RelativeLayout>
Also, your Drink class, vip_package_listgroup.xml and vip_drinks_listitem.xml are also needed. Hope that helps!
I have a problem in expandableListView that is weird with databinding.There is textview of quantity which can be incremented/decremented on button click.The Textview correctly updates at specific position. But when scrolled down the value changes the to textview at different position. Also , when group expanded value move the below item textview.Below are adapter , xml and model class.
public class ProductExpandableListAdapter extends BaseExpandableListAdapter {
private Activity contextActivity;
private ArrayList<ProductItems> productItemsArrayList;
public ProductExpandableListAdapter(ProductActivity productActivity, ArrayList<ProductItems> productItemsArrayList) {
this.contextActivity = productActivity;
this.productItemsArrayList = productItemsArrayList;
}
#Override
public void registerDataSetObserver(DataSetObserver dataSetObserver) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
}
#Override
public int getGroupCount() {
return this.productItemsArrayList.size();
}
#Override
public int getChildrenCount(int i) {
return 1;
}
#Override
public Object getGroup(int i) {
return this.productItemsArrayList.get(i);
}
#Override
public Object getChild(int i, int i1) {
return this.productItemsArrayList.get(i).getProductItemDescription();
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
final ProductItems productItems = productItemsArrayList.get(i);
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
final ProductItemBinding productItemsBinding = DataBindingUtil.inflate(layoutInflater, R.layout.product_items, viewGroup, false);
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.productTitleTextView);
productItemsBinding.productTitleTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_64_pt));
view = productItemsBinding.getRoot();
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.productPriceTextView);
productItemsBinding.productPriceTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_72_pt));
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.qtyTextView);
productItemsBinding.qtyTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_104_pt));
productItemsBinding.setHandler(new QuantityHandler() {
#Override
public void onQuantityIncrement() {
changeQuantity(productItemsBinding, productItems, productItems.getProductItemQty(), Constants.ADDITION);
Toast.makeText(contextActivity, "quantityIncrement : ", Toast.LENGTH_LONG).show();
}
#Override
public void onQuantityDecrement() {
changeQuantity(productItemsBinding, productItems, productItems.getProductItemQty(), Constants.SUBTRACTION);
Toast.makeText(contextActivity, "quantityDecrement : ", Toast.LENGTH_LONG).show();
}
});
productItemsBinding.setProductItems(productItems);
}
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
final ProductItemsChildBinding productItemsChildBinding = DataBindingUtil.inflate(layoutInflater, R.layout.product_items_child, viewGroup, false);
HelveticaNeueFontHelper.applyHelveticaneuelightFont(contextActivity, productItemsChildBinding.productDescriptionTextView);
productItemsChildBinding.productDescriptionTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_64_pt));
productItemsChildBinding.setProductItems(productItemsArrayList.get(i));
view = productItemsChildBinding.getRoot();
}
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public void onGroupExpanded(int i) {
}
#Override
public void onGroupCollapsed(int i) {
}
#Override
public long getCombinedChildId(long l, long l1) {
return 0;
}
#Override
public long getCombinedGroupId(long l) {
return 0;
}
private void changeQuantity(final ProductItemBinding productItemsBinding, ProductItems productItems, ObservableInt observableIntQty, String operand) {
switch (operand) {
case Constants.ADDITION:
if (observableIntQty.get() >= 0) {
observableIntQty.set(observableIntQty.get() + 1);
}
break;
case Constants.SUBTRACTION:
if (observableIntQty.get() > 0) {
observableIntQty.set(observableIntQty.get() - 1);
}
break;
}
contextActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
productItemsBinding.executePendingBindings();
}
});
}
}
<data class="ProductItemBinding">
<variable
name="productItems"
type="com.vtrio.waterapp.data.ProductItems" />
<variable
name="handler"
type="com.vtrio.waterapp.listeners.QuantityHandler" />
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#drawable/rounded_corner_bluegradient"
android:gravity="center_vertical"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:id="#+id/productImageView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
app:imgSrc="#{productItems.productItemImage}" />
<LinearLayout
android:id="#+id/productInfoLinearLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="0.45"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/productTitleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{productItems.productItemTitleName}" />
<TextView
android:id="#+id/productPriceTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{productItems.productItemPrice}" />
</LinearLayout>
<RelativeLayout
android:id="#+id/quantityModRelativeLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_weight="0.25"
android:gravity="center">
<Button
android:id="#+id/subtractQtyButton"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#color/addsubColor"
android:focusable="false"
android:focusableInTouchMode="false"
android:onClick="#{(v) -> handler.onQuantityDecrement()}"
android:text="#string/sub"
android:textColor="#color/addsubTextColor" />
<TextView
android:id="#+id/qtyTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#{Integer.toString(productItems.productItemQty)}" />
<Button
android:id="#+id/addQtyButton"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="#color/addsubColor"
android:focusable="false"
android:focusableInTouchMode="false"
android:onClick="#{(v) -> handler.onQuantityIncrement()}"
android:text="#string/add"
android:textColor="#color/addsubTextColor" />
</RelativeLayout>
</LinearLayout> </layout>
ProductItems
public class ProductItems extends BaseObservable {
private String productItemTitleName;
private String productItemPrice;
private int productItemImage;
private String productItemDescription;
private ObservableInt productItemQty;
private ArrayList<ProductItems> cartItem;
public ProductItems(String productItemTitleName, String productItemPrice, int productItemImage, String productItemDescription, ObservableInt productItemQty) {
this.productItemTitleName = productItemTitleName;
this.productItemPrice = productItemPrice;
this.productItemImage = productItemImage;
this.productItemDescription = productItemDescription;
this.productItemQty = productItemQty;
}
public String getProductItemTitleName() {
return productItemTitleName;
}
public void setProductItemTitleName(String productItemTitleName) {
this.productItemTitleName = productItemTitleName;
}
public String getProductItemPrice() {
return productItemPrice;
}
public void setProductItemPrice(String productItemPrice) {
this.productItemPrice = productItemPrice;
}
public int getProductItemImage() {
return productItemImage;
}
public void setProductItemImage(int productItemImage) {
this.productItemImage = productItemImage;
}
public String getProductItemDescription() {
return productItemDescription;
}
public void setProductItemDescription(String productItemDescription) {
this.productItemDescription = productItemDescription;
}
#Bindable
public ObservableInt getProductItemQty() {
return productItemQty;
}
public void setProductItemQty(ObservableInt productItemQty) {
this.productItemQty = productItemQty;
notifyPropertyChanged(BR.productItemQty);
}
What is the problem and what can be done to solve this.
Maybe the problem is solved already but if not, I would change the getGroupView(...) method (and getChildView likewise) for the case when view is not null like this:
#Override
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
final ProductItems productItems = productItemsArrayList.get(i);
final ProductItemBinding productItemsBinding;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
productItemsBinding = DataBindingUtil.inflate(layoutInflater, R.layout.product_items, viewGroup, false);
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.productTitleTextView);
productItemsBinding.productTitleTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_64_pt));
view = productItemsBinding.getRoot();
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.productPriceTextView);
productItemsBinding.productPriceTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_72_pt));
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.qtyTextView);
productItemsBinding.qtyTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_104_pt));
}
else
{
productItemsBinding = (ProductItemBinding) view.getTag();
}
productItemsBinding.setHandler(new QuantityHandler() {
#Override
public void onQuantityIncrement() {
changeQuantity(productItemsBinding, productItems, productItems.getProductItemQty(), Constants.ADDITION);
Toast.makeText(contextActivity, "quantityIncrement : ", Toast.LENGTH_LONG).show();
}
#Override
public void onQuantityDecrement() {
changeQuantity(productItemsBinding, productItems, productItems.getProductItemQty(), Constants.SUBTRACTION);
Toast.makeText(contextActivity, "quantityDecrement : ", Toast.LENGTH_LONG).show();
}
});
productItemsBinding.setProductItems(productItems);
view.setTag(productItemsBinding);
return view;
}
I want data from my JSON to be displayed in another Activity inside a ListView with 3 columns. I made a Layout for my ListView but that's all
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:descendantFocusability="afterDescendants"
android:orientation="vertical"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp">
<TextView
android:id="#+id/txtViewNumarCumparator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="NumarCumparator" />
<TextView
android:id="#+id/listaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtViewNumarCumparator"
android:layout_marginTop="10dp"
android:text="NumarProduse" />
<TextView
android:id="#+id/sumaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="SumaProdsue" />
I have a JSONObject which retrieves data like this :
{"dataCurenta":"11-08-2017",
"produseSelectate":3,
"pretTotal":605
}
Here is the code :
JSONObject json = new JSONObject();
try {
json.put("dataCurenta", getDate(calendarData.getTimeInMillis()));
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("produseSelectate", listaProdusePreview.getAdapter().getCount());
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("pretTotal", totalPrice);
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("numarVanzare", numarVanzare);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("LISTA", json.toString());
Adapter :
public class CardArrayAdapter extends ArrayAdapter<Card> {
private static final String TAG = "CardArrayAdapter";
private List<Card> cardList = new ArrayList<Card>();
static class CardViewHolder {
TextView line1;
TextView line2;
TextView line3;
}
public CardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public void add(Card object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public Card getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.line1 = (TextView) row.findViewById(R.id.txtViewNumarCumparator);
viewHolder.line2 = (TextView) row.findViewById(R.id.listaProduse);
viewHolder.line3 = (TextView) row.findViewById(R.id.sumaProduse);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
Card card = getItem(position);
viewHolder.line1.setText(card.getNumarCumparator());
viewHolder.line2.setText(card.getListaProduse());
viewHolder.line3.setText(card.getSumaProduse());
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
} }
Object class :
public class Card {
private Integer numarCumparator;
private String listaProduse;
private Integer sumaProduse;
public Card(Integer numarCumparator, String listaProduse, Integer sumaProduse) {
this.numarCumparator = numarCumparator;
this.listaProduse = listaProduse;
this.sumaProduse = sumaProduse;
}
public Integer getNumarCumparator() {
return numarCumparator;
}
public void setNumarCumparator(Integer numarCumparator) {
this.numarCumparator = numarCumparator;
}
public String getListaProduse() {
return listaProduse;
}
public void setListaProduse(String listaProduse) {
this.listaProduse = listaProduse;
}
public Integer getSumaProduse() {
return sumaProduse;
}
public void setSumaProduse(Integer sumaProduse) {
this.sumaProduse = sumaProduse;
}}
Hope the question is clear, I really need to get out from this problem.