I have a RecyclerView that gets inflated in a Fragment. The problem is, when the items count gets more than views height, every item that is in the view will get a width of highest content (I mean all will get wrap content of highest width). In the image it's more specific, also after scrolling those views that will get refreshed will have a correct width (match parent). I already have tried those code suggestions on other questions but still problem exists. here is my code:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.complex_item, parent, false);
return new ViewHolder(itemView);
}
The xml layout for items:
<?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:layout_margin="5dp"
android:id="#+id/baseBg"
android:orientation="vertical">
<LinearLayout
android:id="#+id/expand_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_item_background"
android:foreground="?selectableItemBackground"
android:gravity="center|right"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/textViewTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textColor="#color/colorPage5"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Code snippet that does the fragment replace:
mainPageFrameLayout.removeAllViews();
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainPageFrameLayout, new MojtamaFragment(id, "3"));
ft.commit();
And the mainPageFrameLayout:
<FrameLayout
android:id="#+id/mainPageFrameLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:animateLayoutChanges="true"
android:background="#color/colorPage5" />
The adapter and the onCreateView:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
...
//(this part items is getting generated by a Http Request)
...
recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
return rootView;
}
Images:
Edit: Image explanation: as you can see in image 1 when items numbers gets more than views height items width gets wrap_content instead of match_parent (Image 2 is the correct one that it should be) in image 3 as you can see after i did scroll, items that get's re-instantiated gets correct width. I hope you get the point.
Edit 3: This is whole adapter and viewholder code and imports:
package com.ahrabi.ojekavir.Fragments;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.ahrabi.ojekavir.R;
import com.ahrabi.ojekavir.connector.HttpVolley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Ahrabi2 on 1/10/2018.
*/
#SuppressLint("ValidFragment")
public class MojtamaFragment extends Fragment {
public static final String GET_COMPLEX_LIST_URL = "/Building/getComplexList";
public static final String LOGIN_URL = "/user/Login";
SharedPreferences prefs;
public String firsturl;
private String[] id, title;
private String idCame, complexID;
#SuppressLint("ValidFragment")
public MojtamaFragment(String id, String complexID) {
this.idCame = id;
this.complexID = complexID;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (prefs.getBoolean("net_switch", false)) {
// Your switch is on
Log.v("Requests", "Over Network");
firsturl = prefs.getString("internet_url", getResources().getString(R.string.pref_default_display_internet));
Log.v("Over internet url", firsturl);
} else {
// Your switch is off
Log.v("Requests", "Over Local");
firsturl = prefs.getString("local_url", getResources().getString(R.string.pref_default_display_local));
Log.v("Local url", firsturl);
}
String[] keys = new String[2];
String[] values = new String[2];
keys[0] = "ComplexTypeId";
keys[1] = "regionID";
values[0] = complexID;
values[1] = idCame;
new HttpVolley
().HttpVolleyPost(getActivity(), firsturl + GET_COMPLEX_LIST_URL, keys, values, new HttpVolley.VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(String response) {
if (response.contentEquals("-7")) {
} else {
// response = response.replaceAll("\\", "");
Log.v("Response", response);
String jsonResult = "{" + "\"" + "android" + "\"" + ":" + response
+ "}";
try {
JSONObject jObject = new JSONObject(jsonResult);
// Getting JSON Array from URL
JSONArray android = jObject.getJSONArray("android");
Log.v("android", android.toString());
Log.v("android.length()", "" + android.length());
id = new String[android.length()];
title = new String[android.length()];
for (int i = 0; i < android.length(); i++) {
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
id[i] = c.getString("id");
title[i] = c.getString("Name");
}
recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
return rootView;
}
private void showLoginPopup(String page) {
LayoutInflater curInflate = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View curLayout = curInflate.inflate(R.layout.login_popup,
(ViewGroup) getActivity().findViewById(R.id.mainLinearPopup));
final PopupWindow swindo = new PopupWindow(curLayout,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
swindo.setBackgroundDrawable(new BitmapDrawable());
swindo.setFocusable(true);
// swindo.setAnimationStyle(R.style.PopupWindowAnimation);
swindo.showAtLocation(curLayout, Gravity.BOTTOM,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout bg = (LinearLayout) curLayout
.findViewById(R.id.bgLinearPopup);
LinearLayout loginIV = (LinearLayout) curLayout
.findViewById(R.id.loginIV);
final EditText loginUserName = (EditText) curLayout
.findViewById(R.id.loginUserName);
final EditText loginPassword = (EditText) curLayout
.findViewById(R.id.loginPassword);
if (page.contentEquals("1"))
loginIV.setBackgroundResource(R.drawable.item_brown_bg);
else if (page.contentEquals("3"))
loginIV.setBackgroundResource(R.drawable.item_orange_bg);
bg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
swindo.dismiss();
}
});
loginIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (loginUserName.getText().toString().contentEquals("")){
} else if (loginPassword.getText().toString().contentEquals("")){
} else {
String[] keys = new String[2];
String[] values = new String[2];
keys[0] = "userName";
keys[1] = "password";
values[0] = loginUserName.getText().toString();
values[1] = loginPassword.getText().toString();
new HttpVolley
().HttpVolleyPost(getActivity(), firsturl + LOGIN_URL, keys, values, new HttpVolley.VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(String response) {
if (response.contentEquals("1")) {
} else {
}
}
});
}
}
});
}
private static class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
private RecyclerView recyclerView;
private String[] id, title;
private Context context;
private String complexID;
private MojtamaFragment mojtamaFragment;
public SimpleAdapter(RecyclerView recyclerView, String[] id, String[] title, Context context, String complexID,MojtamaFragment mojtamaFragment) {
this.recyclerView = recyclerView;
this.id = id;
this.title = title;
this.context = context;
this.complexID = complexID;
this.mojtamaFragment = mojtamaFragment;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.complex_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textViewTitle.setText(title[position]);
if (complexID.contentEquals("1"))
holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage6));
else if (complexID.contentEquals("3"))
holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage5));
}
#Override
public int getItemCount() {
return id.length;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewTitle;
private LinearLayout expandButton;
public ViewHolder(View itemView) {
super(itemView);
expandButton = itemView.findViewById(R.id.expand_button);
textViewTitle = itemView.findViewById(R.id.textViewTitle);
expandButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) recyclerView.findViewHolderForAdapterPosition(getAdapterPosition());
mojtamaFragment.showLoginPopup(complexID);
}
}
}
}
After so much editing and experiencing i found a part of code from my xml layout (the one that FrameLayout is in it and fragment gets replaced by it) has something to do with error:
<android.support.constraint.ConstraintLayout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.ahrabi.ojekavir.CityActivity"
tools:showIn="#layout/activity_city">
after removing app:layout_behavior and changing ContraintLayout to some Linear or RelativeLayout problem now is gone.
I don't know why this part raises such problem, but it has definitely a reason.
Related
I am getting a null pointer exception on the following statement within my recyclersetup method.
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
It is due to the following statement not setting a pointer to recyclerView in the previous statement which is
recyclerView = getView().findViewById(R.id.check_in_recent_row);
I cannot determine why I am not getting the recyclerView pointer established via this statement. the ID for the data is correct. What am I missing?
This is the entire fragment code
CheckInRecentList.java
package com.example.checkingin;
import android.content.Context;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProvider.Factory;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CheckInRecentList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CheckInRecentList#newInstance} factory method to
* create an instance of this fragment.
*/
public class CheckInRecentList extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView recyclerView;
private RecyclerView.Adapter checkInListAdapter;
//private RecyclerView.LayoutManager layoutManager;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MainViewModel mViewModel;
private CheckInListAdapter adapter;
private MainViewModelProviderFactory viewModelFactory;
private TextView checkInLastDateTime;
private TextView checkInTitle;
private TextView checkInDestinationName;
private TextView checkInComments;
private OnFragmentInteractionListener mListener;
public CheckInRecentList() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CheckInRecentList.
*/
// TODO: Rename and change types and number of parameters
public static CheckInRecentList newInstance(String param1, String param2) {
CheckInRecentList fragment = new CheckInRecentList();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate: On Create");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// These were originally set up from the recycler view add to the fragment
// recyclerView = findViewById(R.id.check_in_recent_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
//recyclerView.setHasFixedSize(true);
/*
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
*/
// specify an adapter (see also next example)
//checkInListAdapter = new CheckInListAdapter();
// recyclerView.setAdapter(checkInListAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "onCreateView: On Create View");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.recycler_view_item, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Log.i(TAG, "onButtonPressed: ");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG, "onAttach: OnAttach");
viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
Log.i(TAG,"OnAttach completed");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated: On Activity Created");
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
checkInTitle = getView().findViewById(R.id.checkInTitle);
checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
checkInComments = getView().findViewById(R.id.checkInComments);
recyclerSetup();
Log.i(TAG,"OnActivityCreated: Recycler SetUp");
//listenerSetup();
//Log.i(TAG, "onActivityCreated: Listener SetUp");
observerSetup();
Log.i(TAG, "onActivityCreated: Observer SetUp");
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach: ");
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void clearFields() {
checkInLastDateTime.setText("");
checkInDestinationName.setText("");
checkInTitle.setText("");
checkInComments.setText("");
}
private void listenerSetup() {
ImageButton editCheckInButton = getView().findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = getView().findViewById(R.id.checkInResendButton);
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "listenerSetup: ");
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
}
});
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
private void observerSetup() {
Log.i(TAG, "observerSetup:");
if(mViewModel.getAllCheckIn() != null)
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
adapter.setCheckInList(allCheckIn);
}
});
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>() {
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
if (allCheckIn.size() > 0) {
Log.i(TAG, "onChanged: all check in size greater than zero");
checkInLastDateTime.setText(allCheckIn.get(0).getCheckInLastDateTime());
Log.i(TAG, "onChanged: running again");
checkInDestinationName.setText(allCheckIn.get(0).getCheckInDestinationName());
checkInTitle.setText(allCheckIn.get(0).getCheckInTitle());
checkInComments.setText(allCheckIn.get(0).getCheckInComments());
} else {
checkInLastDateTime.setText("None Found");
}
}
});
}
private void recyclerSetup() {
Log.i(TAG, "recyclerSetup: ");
adapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
//recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
}
}
The following are the xml files for the fragment
fragment_check_in_recent_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".CheckInRecentList">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/check_in_recent_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/recycler_view_item"/>
</FrameLayout>
and recycler_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="#+id/check_in_recent_row"
android:layout_width="389dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:padding="30dp">
<TableRow
android:layout_width="346dp"
android:layout_height="match_parent">
<TextView
android:id="#+id/checkInLastDateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="#+id/checkInTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/checkInDestinationName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageButton
android:id="#+id/checkInEditButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_edit"
android:tooltipText="Edit Check In" />
<ImageButton
android:id="#+id/checkInResendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_share"
android:tooltipText="Resend Check In" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/checkInComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
CheckInListAdapter
package com.example.checkingin;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
private int checkInListLayout;
private List<CheckInTable> checkInList;
public CheckInListAdapter(int layoutId) {
checkInListLayout = layoutId;
}
public void setCheckInList(List<CheckInTable> allCheckIn) {
checkInList = allCheckIn;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return checkInList == null ? 0 : checkInList.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder: ");
View view = LayoutInflater.from(
parent.getContext()).inflate(checkInListLayout, parent, false);
ViewHolder checkInListViewHolder = new ViewHolder(view);
return checkInListViewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView checkInLastDateTime = holder.checkInLastDateTime;
TextView checkInTitle = holder.checkInTitle;
TextView checkInDestinationName = holder.checkInDestinationName;
TextView checkInComments = holder.checkInComments;
ImageView checkInEditButton = holder.checkInEditButton;
ImageView checkInResendButton = holder.checkInResendButton;
Log.i(TAG, "onBindViewHolder: ");
checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
checkInComments.setText(checkInList.get(listPosition).getCheckInComments());
holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);
ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
}
}
);
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView checkInLastDateTime;
TextView checkInTitle;
TextView checkInDestinationName;
TextView checkInComments;
ImageView checkInEditButton;
ImageView checkInResendButton;
ViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "ViewHolder: ");
checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
checkInTitle = itemView.findViewById(R.id.checkInTitle);
checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
checkInComments = itemView.findViewById(R.id.checkInComments);
checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
}
Your RecyclerView's ID is check_in_recent_recycler_view. Your findViewById call is using check_in_recent_row. These need to match.
I'm new to Android Studio. I'm trying to custom a Fragment automatically created by the IDE using the option create -> new Fragment (List). I'm not able to show the List retrieved from an http page, but if I manually add items to my list, the emulator let me see it. How can I solve this problem?
municipioFragment.java
package com.example.is2_app.ui.municipio;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.is2_app.R;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class municipioFragment extends Fragment {
// TODO: Customize parameters
private int mColumnCount = 1;
private List<News> lstNews;
private OnListFragmentInteractionListener mListener;
public municipioFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstNews = new ArrayList<>();
getURL();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_municipio_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(News item);
}
public void getURL() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("http://www.comune.candida.av.it").get();
Element content = doc.getElementById("b370");
Elements subcontent = content.getElementsByTag("p");
String Text = null;
String Href = null;
int i = 0;
for (Element link : subcontent) {
Href = link.attr("href");
Text = link.text();
builder.append("\n").append(Text);
i = i + 1;
lstNews.add(new News(Integer.toString(i), Text));
}
} catch (IOException e) {
builder.append("Error: ").append(e.getMessage()).append("\n");
}
}
}).start();
}
}
MunicipioRecyclerViewAdapter.java
package com.example.is2_app.ui.municipio;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.is2_app.R;
import com.example.is2_app.ui.municipio.municipioFragment.OnListFragmentInteractionListener;
import java.util.List;
public class MymunicipioRecyclerViewAdapter extends RecyclerView.Adapter<MymunicipioRecyclerViewAdapter.ViewHolder> {
private final OnListFragmentInteractionListener mListener;
List<News> mData;
public MymunicipioRecyclerViewAdapter(List<News> mData, OnListFragmentInteractionListener listener) {
this.mData = mData;
this.mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_municipio, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
//holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mData.get(position).getId());
holder.mContentView.setText(mData.get(position).getContent());
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.item_number);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
fragment_municipio.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" /> </LinearLayout>
fragment_municipio_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView 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:id="#+id/list"
android:name="com.example.is2_app.ui.municipioFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ui.municipio.municipioFragment"
tools:listitem="#layout/fragment_municipio" />
So getUrl() is running in a Thread. In addition, getting the Document with JSoup is gonna need some time. This means that onCreateView will probably run before your lstNews is filled with the data you are scraping from the Document.
So you want to update your dataset; then, you want to notify your Adapter that your dataset changed.
Add this method to your Adapter
public void updateData(List<News> mData) {
this.mData = mData;
this.notifyDataSetChanged();
}
And after the for loop in getUrl(), you want to do the following:
runOnUiThread(new Runnable() {
#Override
public void run() {
recyclerViewAdapter.updateData(lstNews);
}
});
Where, recyclerViewAdapter is defined alongside recyclerView and initialized in the onCreateView.
So the following line:
recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
Will become:
recyclerViewAdapter = new MymunicipioRecyclerViewAdapter(lstNews, mListener);
recyclerView.setAdapter(recyclerViewAdapter);
Toast On ArrayAdapter
How to Show Toast message On QuoteArrayAdapter OnClick textViewQuoteLike
Show message Like is Done
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
/*Toast.makeText(Need Activity, "Like is done.",
Toast.LENGTH_LONG).show();*/
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
If there is a way that in HomeFragment Put it, Please give an example
QuoteArrayAdapter.java
package com.example.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.R;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class QuoteArrayAdapter extends ArrayAdapter<QuoteDataModel> {
List<QuoteDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public QuoteArrayAdapter(Context context, List<QuoteDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public QuoteDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.quote_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
QuoteDataModel item = getItem(position);
vh.textViewQuoteContent.setText(item.getQuoteContent());
vh.textViewProfileName.setText(item.getProfileName());
vh.textViewQuoteLike.setText("پسندیدم ("+item.getQuoteLike()+")");
vh.textViewQuoteCopy.setText("کپی کردن");
vh.textViewQuoteShare.setText("اشتراک گزاری");
vh.textViewQuoteId.setText(item.getQuoteId());
Picasso.with(context).load(item.getProfilePhoto()).placeholder(R.drawable.empty_profile_photo).error(R.drawable.empty_profile_photo).transform(new CircleTransform()).into(vh.imageViewProfilePhoto);
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final ImageView imageViewProfilePhoto;
public final TextView textViewQuoteContent;
public final TextView textViewProfileName;
public final TextView textViewQuoteLike;
public final TextView textViewQuoteCopy;
public final TextView textViewQuoteShare;
public final TextView textViewQuoteId;
private ViewHolder(RelativeLayout rootView, ImageView imageViewProfilePhoto, TextView textViewQuoteContent, TextView textViewProfileName, TextView textViewQuoteLike, TextView textViewQuoteCopy, TextView textViewQuoteShare, TextView textViewQuoteId) {
this.rootView = rootView;
this.imageViewProfilePhoto = imageViewProfilePhoto;
this.textViewQuoteContent = textViewQuoteContent;
this.textViewProfileName = textViewProfileName;
this.textViewQuoteLike = textViewQuoteLike;
this.textViewQuoteCopy = textViewQuoteCopy;
this.textViewQuoteShare = textViewQuoteShare;
this.textViewQuoteId = textViewQuoteId;
}
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
}
static class GetDataLike extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Nullable
#Override
protected String doInBackground(String... params) {
String quoteId = params[0];
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_quote_like/?platform=true&id="+quoteId);
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_LIKE);
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
JSONObject innerObject = array.getJSONObject(jIndex);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
return quote_like;
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
public class CircleTransform implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
#Override
public String key() {
return "circle";
}
}
}
HomeFragment.java
package com.example;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private ListView listView;
private ArrayList<QuoteDataModel> list;
private QuoteArrayAdapter adapter;
private TextView likeCurrent;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, null);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
adapter = new QuoteArrayAdapter(getActivity(), list);
/**
* Getting List and Setting List Adapter
*/
listView = (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Check internet connection
*/
if (!MainActivity.NetworkUtil.isOnline(getActivity().getApplicationContext())) {
Toast.makeText(getActivity(), "اتصال به اینترنت برقرار نیست",
Toast.LENGTH_LONG).show();
}
new GetDataHome().execute();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
new GetDataHome().execute();
}
}
});
/*
likeCurrent = (TextView) getActivity().findViewById(R.id.textViewQuoteLike);
likeCurrent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
likeCurrent.setText("Boiling Point K");
}
});*/
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataHome extends AsyncTask<Void, Void, Void> {
ContentLoadingProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Bar for User Interaction
*/
progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
progressBar.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_home/?platform=true");
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "Home" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_HOME);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
QuoteDataModel model = new QuoteDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String profile_photo = innerObject.getString(Keys.KEY_PROFILE_PHOTO);
String profile_name = innerObject.getString(Keys.KEY_PROFILE_NAME);
String profile_link = innerObject.getString(Keys.KEY_PROFILE_LINK);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
String quote_id = innerObject.getString(Keys.KEY_QUOTE_ID);
String quote_content = innerObject.getString(Keys.KEY_QUOTE_CONTENT);
String quote_category = innerObject.getString(Keys.KEY_QUOTE_CATEGORY);
/**
* Getting Object from Object "other"
*/
//JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
//String other = otherObject.getString(Keys.KEY_NAME_SUB);
model.setProfilePhoto(profile_photo);
model.setProfileName(profile_name);
model.setProfileLink(profile_link);
model.setQuoteLike(quote_like);
model.setQuoteId(quote_id);
model.setQuoteContent(quote_content);
model.setQuoteCategory(quote_category);
/**
* Adding data in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
/**
* Progress Bar for User Interaction
*/
progressBar.hide();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
}
}
}
}
quote_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageViewProfilePhoto"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="5dp"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:src="#drawable/empty_profile_photo" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/imageViewProfilePhoto">
<TextView
android:id="#+id/textViewQuoteContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Quote Content" />
<TextView
android:id="#+id/textViewProfileName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Profile Name" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textViewQuoteCopy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:clickable="true"
tools:text="Copy" />
<TextView
android:id="#+id/textViewQuoteShare"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Share" />
<TextView
android:id="#+id/textViewQuoteLike"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Like" />
</LinearLayout>
</LinearLayout>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textViewQuoteId"
android:visibility="invisible" />
</RelativeLayout>
fragment_home.xml
<?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:id="#+id/parentLayout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
<ListView app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</RelativeLayout>
You just need a context, so:
Toast.makeText(rootView.getContext(), "Like is done.",
Toast.LENGTH_LONG).show();
But you need to make rootView final first:
public static ViewHolder create(final RelativeLayout rootView){...
^^
I want to Increase and decrease value of qty on clicked.
i Used ImageView for decrease and Increase the value in middle i used TextView for showing the value.
this thing is completely work in the Activity but i want perform this operation in ListView.
Here the complete code and it is working on simple Activity.
qty.java
public class qty extends AppCompatActivity {
int minteger = 0;
ImageView decrease;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.raw_order);
decrease=(ImageView) findViewById(R.id.decrease);
decrease.setEnabled(false);
}
public void increaseInteger(View view) {
minteger = minteger + 1;
display(minteger);
}public void decreaseInteger(View view) {
minteger = minteger - 1;
display(minteger);
}
private void display(int number) {
TextView displayInteger = (TextView) findViewById(
R.id.integer_number);
displayInteger.setText("" + number);
}
}
raw_order.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/decrease"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="#drawable/minus"
android:layout_marginTop="05dp"
android:textColor="#000"
android:onClick="decreaseInteger"
/>
<TextView
android:id="#+id/integer_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_marginTop="16dp"
android:textSize="20dp" />
<ImageView
android:id="#+id/increase"
android:layout_marginTop="05dp"
android:layout_width="30dp"
android:onClick="increaseInteger"
android:layout_height="wrap_content"
android:src="#drawable/plus"
android:textColor="#000"/>
</LinearLayout>
And i want to perform this same thing in ListView
ListViewadapterorder.java
package omcommunication.orderdesign;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static android.media.CamcorderProfile.get;
public class ListViewAdapterorder extends BaseAdapter implements ListAdapter{
Context cntx;
SparseIntarray sia; // class variable
// SessionManager session;
AlertDialog.Builder alertDialogBuilder;
View view;
int minteger = 0;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
private boolean status;
public static final String KEY_EMP_ID = "id";
public static final String TAG_ID = "o_id";
ArrayList<String> o_aid = new ArrayList<String>();
ArrayList<String> o_aproduct = new ArrayList<String>();
ArrayList<String> o_aqty = new ArrayList<String>();
ArrayList<String> o_atotal = new ArrayList<String>();
public ListViewAdapterorder(Context context,
ArrayList<String> o_id,
ArrayList<String> o_product,
ArrayList<String> o_qty,
ArrayList<String> o_total
) {
// TODO Auto-generated constructor stub
cntx = context;
o_aid = o_id;
o_aproduct = o_product;
o_aqty = o_qty;
o_atotal = o_total;
alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage("Do You Want To Call....");
/* session = new SessionManager(context);
HashMap<String, String> user = session.getUserDetails();
uid = user.get(SessionManager.KEY_ID);
*/
}
#Override
public int getCount() {
return o_aid.size();
}
#Override
public Object getItem(int position) {
return o_aid.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
TextView mname , pmethod2, pamount3, premark4;
final ImageView increase,decrease;
final TextView displayInteger;
inflater = (LayoutInflater) cntx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(cntx);
convertView = inflater.inflate(R.layout.raw_order, parent,
false);
decrease = (ImageView) convertView.findViewById(R.id.decrease);
increase= (ImageView) convertView.findViewById(R.id.increase);
mname = (TextView) convertView.findViewById(R.id.mname);
mname.setText(" " + o_aproduct.get(position));
sia = new SparseIntarray(data.size());
displayInteger = (TextView) convertView.findViewById(R.id.integer_number);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int count = sia.get(position);
count++;
resultp.put(cout);
displayInteger.setText("" + count);
}
});
return convertView;
}
private class SparseIntarray {
public SparseIntarray(int size) {
}
}
}
you can use SparseIntArray to store the value count for each position
in the listAdapter class define an instance variable
SparseIntArray sia; // class variable
.. inside listAdapter constructor
sia = new SparseIntArray(data.size());
then in OnClick event
public void onItemClick(...) {
int count = sia.get(position)
// now increment or decrement as per your requirement
// coutn++; or count--; and save it
sia.put(position, count);
Edit 1:
set OnClick listeners to your increase decrease imageViews in the getView() method,
final displayInteger = (TextView) convertView.findViewById(R.id.integer_number);
increase.setOnClikcListener(new OnClickListener {
#Override
public void onClick(View view)
{
int count = sia.get(position);
count++;
sia.put(position, count);
displayInteger.setText("" + count);
});
you can do the same with your decrease view
Make an OnLickListener for the image view and call the methods,
For the list view you need to make an OnItemSelectedListener Or OnItemClickListener
First You Need To Give The ImageView an ID; Then Do It Like This
In On Create :::
ImageView img=(ImageView)findViewById(R.id.imageview);
img.setOnClickListener(imgclick);
Then In The Class Body ::::
OnClickListener imgclick=new OnClickListener() {
#Override
public void onClick(View view) {
//Call The Methods Like Increase Number Or Decrease
}
};
Hi all i have problemm that getView() is not called. Sup please. And in project i am using ViewPager. So maybe it's becouse of that
Here my MainActivity
package com.uinleader.animewatcher;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private List<View> pages;
private View recent;
private View top_seven;
private ViewPager mPager;
private final ArrayList<Parsed> info = new ArrayList<Parsed>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUi();
LVInit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(android.R.menu.main, menu);
return true;
}
private void initUi() {
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
recent = inflater.inflate(R.layout.recent, null);
recent.setTag(getString(R.string.recent));
top_seven = inflater.inflate(R.layout.top_seven, null);
top_seven.setTag(getString(R.string.top));
pages.add(recent);
pages.add(top_seven);
PAdapter adapter = new PAdapter(pages);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
mPager.setCurrentItem(0);
}
private void LVInit() {
LayoutInflater inflater = LayoutInflater.from(this);
Parsed one = new Parsed("One", "1", R.drawable.ic_launcher);
Parsed two = new Parsed("Two", "2", R.drawable.ic_launcher);
Parsed three = new Parsed("Three", "3", R.drawable.ic_launcher);
View v = inflater.inflate(R.layout.top_seven, null);
info.add(one);
info.add(two);
info.add(three);
ListView lv = (ListView) v.findViewById(R.id.listView1);
MArrayAdapter radapter = new MArrayAdapter(MainActivity.this, R.id.listView1, info);
lv.setAdapter(radapter);
}
}
Here is adapter
package com.uinleader.animewatcher;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by uinleader on 28.09.13.
*/
public class MArrayAdapter extends ArrayAdapter<Parsed> {
private final Activity activity;
private final ArrayList<Parsed> items;
public MArrayAdapter(Activity a, int textViewResourceId, ArrayList<Parsed> items) {
super(a, textViewResourceId, items);
activity = a;
this.items = items;
Log.e("ListViewDebug", "Inside Adapter");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.e("ListViewDebug", "Start Function");
View view = convertView;
ViewHolder holder;
if (view == null) {
Log.e("ListViewDebug", "In First IF");
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.anime_title);
holder.ep_num = (TextView) view.findViewById(R.id.ep_number);
holder.ep_preview = (ImageView) view.findViewById(R.id.ep_preview);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
Parsed item = items.get(position);
if(item!=null) {
holder.title.setText(item.anime_title);
holder.ep_num.setText("Episode: "+item.ep_num);
holder.ep_preview.setImageResource(item.img);
}
return view;
}
#Override
public int getCount() {
return items.size();
}
private static class ViewHolder {
public TextView title;
public TextView ep_num;
public ImageView ep_preview;
}
}
Here is my class for data. And XML's
package com.uinleader.animewatcher;
/**
* Created by uinleader on 28.09.13.
*/
public class Parsed {
public String anime_title;
public String ep_num;
public int img;
public Parsed (String anime_title, String ep_num, int img ){
this.anime_title = anime_title;
this.ep_num = ep_num;
this.img = img;
}
}
XML for list.
<?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" >
<ListView
android:id="#+id/listView1"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</ListView>
</LinearLayout>
XML for row's
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
>
<ImageView
android:layout_width="200px"
android:layout_height="200px"
android:id="#+id/ep_preview"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/anime_title"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/ep_preview" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ep_number"
android:layout_below="#+id/anime_title"
android:layout_toRightOf="#+id/ep_preview" />
</RelativeLayout>
The setContentView(R.layout.activity_main); already "inflates" the current layout the activity is using..i don't why you are inflating other stuff in the "init" methods, that is probably why nothing is being called because the activity remains displaying the view set on R.layout.activity_main.
ArrayAdapter works a bit differently than BaseAdapter - which is for what you're implementing your getView
I suggest several options to fix :
change your ArrayAdapter to BaseAdapter
or use the built in ArrayList that comes with the ArrayList adapter
in your constructor write the following :
public MArrayAdapter(Activity a, int textViewResourceId, ArrayList<Parsed> items) {
super(a, textViewResourceId, items); //<== call to super instantiates the items
activity = a;
//ArrayListAdapter has a built in arrayList - use it
Log.e("ListViewDebug", "Inside Adapter");
}
change your getView to this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.e("ListViewDebug", "Start Function");
View view = convertView; // **note why do you allocate again? just write convertview everywhere instead of view**
ViewHolder holder;
if (view == null) {
Log.e("ListViewDebug", "In First IF");
//**I recommend instantiating the inflater once inside the constructor**
LayoutInflater inflater =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.anime_title);
holder.ep_num = (TextView) view.findViewById(R.id.ep_number);
holder.ep_preview = (ImageView) view.findViewById(R.id.ep_preview);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
Parsed item = (Parsed)getItem(position); //<==== this
if(item!=null) {
holder.title.setText(item.anime_title);
holder.ep_num.setText("Episode: "+item.ep_num);
holder.ep_preview.setImageResource(item.img);
}
return
view;
}