I have an activity that contain a fragment which contains a recycler view and i use recycler view adapter to fill the recycler view with data and i use layout which contains 2 text view and 3 buttons when rotate emulator the language changed so I save the state of the fragment in activity, the language doesn't changed but the text on buttons doesn't appear I try to save state of text in fragment but i get error null pointer exception for button object
the fragment code
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.daily_azkaar_fragment,container, false);
rv = (RecyclerView) view.findViewById(R.id.recyclerviewcard);
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(rv);
activity = getActivity().getIntent().getIntExtra("activity", 3);
position = getActivity().getIntent().getIntExtra("position", 3);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
rv.scrollToPosition(position);
settings= getActivity().getSharedPreferences("MyPrefs", 0);
favourite=loadArray("fav",getActivity());
favourite_evening=loadArray("fav_evening",getActivity());
for(int i=0;i<favourite.length;i++)
Log.d("msg ",String.valueOf(favourite[i]));
if (settings.getBoolean("is_first_time_presses", true)) {
//the app is being launched for first time, do something
Log.d("TAG", "First time Presses");
settings.edit().putBoolean("is_first_time_presses", false).commit();
storePresses(presses,"presses",0);
storePresses(presses_evening,"presses_evening",0);
} else {
//second time launch..
presses=loadPresses("presses");
presses_evening=loadPresses("presses_evening");
for(int i=0;i<presses.length;i++)
Log.d("presses ",String.valueOf(presses[i]));
}
if (settings.getBoolean("is_sett", true)) {
//the app is being launched for first time, do something
Log.d("TAG", "First time");
settings.edit().putBoolean("is_sett", false).commit();
storeArraySettings(settingsArray,"sett",true,getActivity());
} else {
//second time launch..
settingsArray=loadArray("sett",getActivity());
for(int i=0;i<settingsArray.length;i++)
Log.d("msg ",String.valueOf(settingsArray[i]));
}
if(activity == 3){
azkarForms=getSunsetFavourites("fav","presses", this.getContext());
adapter=new RecyclerFavouriteAdapter(azkarForms,getActivity(),activity,0);
rv.setAdapter(adapter);
adapter.setClickListener(this);
}
else{
azkarForms=getSunsetFavourites("fav_evening","presses_evening", this.getContext());
adapter=new RecyclerFavouriteAdapter(azkarForms,getActivity(),activity,0);
rv.setAdapter(adapter);
Button next=view.findViewById(R.id.next);
if(savedInstanceState != null)
next.setText(savedInstanceState.getString("next"));
adapter.setClickListener(this);
}
return view;
}
private ArrayList<AzkarForm> getSunsetFavourites(String arrayName, String pressesArray, Context mContext) {
AzkaarData azkaarData = new AzkaarData(mContext);
list = new ArrayList<>();
int size = settings.getInt(arrayName + "_size", 0);
Boolean[] array = new Boolean[size];
int[] numPresses = new int[size];
ArrayList<MyFavourites> myResults = new ArrayList<MyFavourites>();
MyFavourites myFavourites;
for (int i = 0; i < size; i++) {
array[i] = settings.getBoolean(arrayName + "_" + i, true);
numPresses[i] = settings.getInt(pressesArray + "_" + i, 0);
myFavourites=new MyFavourites(i,array[i],numPresses[i]);
myResults.add(myFavourites);
}
if (myResults != null)
list = azkaarData.getArrayListDataFav(myResults,activity, 0);
return list;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
savedInstanceState.putString("next", next.getText().toString());
}
adapter code
} else if (activity == 3) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_details,parent,false);
holder=new MyViewHolder(view,activity,c);
return holder;
} else if (activity == 4) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_details,parent,false);
holder=new MyViewHolder(view,activity,c);
return holder;
}
layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="6">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:layout_marginTop="20dp"
android:weightSum="6">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/icon"
android:layout_weight="2"
android:src="#drawable/favorite_border"
android:clickable="true"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="#string/add_zekr_txt"
android:textSize="26sp"/>
</LinearLayout>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/cardview"
android:layout_weight="4">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:id="#+id/relative">
<TextView
android:id="#+id/sample"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:text="#string/sample_zekr"
android:textIsSelectable="true"
android:textSize="20dp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:layout_below="#+id/cardview"
android:weightSum="5">
<Button
android:text="3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/count"
android:layout_weight="2"
android:layout_gravity="center"
android:background="#drawable/btnborder"
android:layout_margin="10dp"/>
<Button
android:text="#string/num_press"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/press"
android:layout_weight="1"
android:background="#drawable/btncircle"
android:layout_margin="10dp"/>
<Button
android:text="#string/next"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/next"
android:layout_weight="2"
android:background="#drawable/btnborder"
android:layout_margin="10dp"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
fragment layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerviewcard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></android.support.v7.widget.RecyclerView>
</LinearLayout>
Use override method onConfigurationChanged() that will help you with orientation change problems.
Related
Here is my code.i want to put 3 recyclerViews in my layout but it is very slow on device while running. If there is 2 recyclerview it works smooth but if 3 slow very :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:id="#+id/scroll_view"
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"
tools:context=".fragments.MainFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#color/blacker"
android:textStyle="bold"
android:textSize="18sp"
android:text="Техника для офиса"
android:layout_marginTop="20dp"
android:layout_marginLeft="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp" />
<android.support.v7.widget.RecyclerView
android:nestedScrollingEnabled="false"
android:fillViewport="true"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:id="#+id/recyclerView_popular_goods"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
<TextView
android:textColor="#color/blacker"
android:textStyle="bold"
android:textSize="18sp"
android:text="Компьютерная техника"
android:layout_marginTop="20dp"
android:layout_marginLeft="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp" />
<android.support.v7.widget.RecyclerView
android:nestedScrollingEnabled="false"
android:fillViewport="true"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:id="#+id/recyclerView_competitive_goods"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
<TextView
android:textColor="#color/blacker"
android:textStyle="bold"
android:textSize="18sp"
android:text="Канцелярские товары"
android:layout_marginTop="20dp"
android:layout_marginLeft="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp" />
<android.support.v7.widget.RecyclerView
android:visibility="gone"
android:fillViewport="true"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:id="#+id/recyclerView_stationery_goods"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
</LinearLayout>
Please if somebody had such kind of problem please help me to fix my issue.
I tried Nested scrollview and setNestedScrollingEnabled = false.but nothing helps
Here is my Activity
#SuppressLint("ValidFragment")
public class MainFragment extends BasicFragment implements
MainFragmentView, PopularGoodsAdapter.ProductListener {
#BindView(R.id.scroll_view)
NestedScrollView mScrollView;
#BindView(R.id.recyclerView_stationery_goods)
RecyclerView mRecyclerViewStationeryGoods;
#BindView(R.id.recyclerView_popular_goods)
RecyclerView mRecyclerViewPopularGoods;
#BindView(R.id.recyclerView_competitive_goods)
RecyclerView mRecyclerViewCompetitiveGoods;
#BindView(R.id.imageSlider)
SliderView mSliderView;
#Inject
Navigator mNavigator;
#Inject
#Named(DISPLAY_WIDTH)
int mDisplayWidth;
#InjectPresenter
MainFragmentPresenter mPresenter;
List<Product> list1;
List<Product> list2;
List<Product> list3;
private PopularGoodsAdapter mAdapterPopularGoods;
private PopularGoodsAdapter mAdapterPopularGoods2;
private PopularGoodsAdapter mAdapterPopularGoods3;
private LayoutAnimationController layoutAnimationController;
private List<String> images;
#SuppressLint("ValidFragment")
public MainFragment() {
}
private void initView(View view) {
ButterKnife.bind(this,view);
images = new LinkedList<>();
images.add("https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260");
images.add("https://images.pexels.com/photos/929778/pexels-photo-929778.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260");
images.add("https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260");
mSliderView.setSliderAdapter(new SliderAdapterExample(getContext(), images, "mainPage"));
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
LinearLayoutManager layoutManager2 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
LinearLayoutManager layoutManager3 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
mRecyclerViewPopularGoods.setLayoutManager(layoutManager);
layoutAnimationController = AnimationUtils.loadLayoutAnimation(getContext(),R.anim.layout_item_from_left);
list1 = new LinkedList<>();
mRecyclerViewPopularGoods.setLayoutAnimation(layoutAnimationController);
mRecyclerViewCompetitiveGoods.setLayoutManager(layoutManager2);
list2 = new LinkedList<>();
mRecyclerViewCompetitiveGoods.setLayoutAnimation(layoutAnimationController);
mRecyclerViewStationeryGoods.setLayoutManager(layoutManager3);
list3 = new LinkedList<>();
mRecyclerViewStationeryGoods.setLayoutAnimation(layoutAnimationController);
mRecyclerViewPopularGoods.setAdapter(mAdapterPopularGoods = new PopularGoodsAdapter(getContext(),list1,mDisplayWidth,"popular",this));
mRecyclerViewCompetitiveGoods.setAdapter(mAdapterPopularGoods2 = new PopularGoodsAdapter(getContext(),list2,mDisplayWidth,"competitive",this));
mRecyclerViewStationeryGoods.setAdapter(mAdapterPopularGoods3 = new PopularGoodsAdapter(getContext(),list3,mDisplayWidth,"stationery",this));
mRecyclerViewPopularGoods.setNestedScrollingEnabled(false);
mRecyclerViewCompetitiveGoods.setNestedScrollingEnabled(false);
mRecyclerViewStationeryGoods.setNestedScrollingEnabled(false);
getLoadingDialog().showDialog(getFragmentManager());
mPresenter.GET_TOP_HOME_VIEW();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container,
false);
initView(view);
return view;
}
#OnClick({R.id.item_sellers,
R.id.item_price_request,R.id.item_price_competitions})
void Onclick(View view) {
switch (view.getId()) {
case R.id.item_sellers:
mNavigator.toSellersActivty(getContext());
break;
case R.id.item_price_request:
mNavigator.toPriceRequestActivty(getContext());
break;
case R.id.item_price_competitions:
mNavigator.toCompetitionsActivty(getContext());
break;
}
}
#Override
public void initTopHomeView(List<HomeViewObject> result) {
if (null != result ) {
if (result.size() >= 1 && null != result.get(0)) {
list1.addAll(result.get(0).getTopProducts());
mAdapterPopularGoods.notifyDataSetChanged();
mRecyclerViewPopularGoods.setLayoutAnimation(layoutAnimationController);
}
if (result.size() >= 2 && null != result.get(1)) {
list2.addAll(result.get(1).getTopProducts());
mAdapterPopularGoods2.notifyDataSetChanged();
mRecyclerViewPopularGoods.setLayoutAnimation(layoutAnimationController);
}
if (result.size() >= 3 && null != result.get(2)) {
list3.addAll(result.get(2).getTopProducts());
mAdapterPopularGoods3.notifyDataSetChanged();
mRecyclerViewStationeryGoods.setLayoutAnimation(layoutAnimationController);
}
}
}
#Override
public void stopProgress() {
getLoadingDialog().hideDialog();
}
#Override
public void onProductClicked(Product product) {
mNavigator.toProductActivity(getContext(),product);
}
}
Is there any mistake?
Try the following -
Try to put all the views inside NestedScrollView i.e, root view.
Set recyclerView.setNestedScrollingEnabled(false); for both the recyclerViews in your xml.
Change your recycler view's android:layout_height="match_parent" to android:layout_height="wrap_content" and then use Nested scrollView with recyclerView.setNestedScrollingEnabled(false);
try to change your ScrollView with NestedScrollViewand Change your recycler view's android:layout_height="match_parent" to android:layout_height="wrap_content" :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
android:id="#+id/scroll_view"
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"
tools:context=".fragments.MainFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#color/blacker"
android:textStyle="bold"
android:textSize="18sp"
android:text="Техника для офиса"
android:layout_marginTop="20dp"
android:layout_marginLeft="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp" />
<android.support.v7.widget.RecyclerView
android:nestedScrollingEnabled="false"
android:fillViewport="true"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:id="#+id/recyclerView_popular_goods"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:textColor="#color/blacker"
android:textStyle="bold"
android:textSize="18sp"
android:text="Компьютерная техника"
android:layout_marginTop="20dp"
android:layout_marginLeft="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp" />
<android.support.v7.widget.RecyclerView
android:nestedScrollingEnabled="false"
android:fillViewport="true"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:id="#+id/recyclerView_competitive_goods"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:textColor="#color/blacker"
android:textStyle="bold"
android:textSize="18sp"
android:text="Канцелярские товары"
android:layout_marginTop="20dp"
android:layout_marginLeft="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp" />
<android.support.v7.widget.RecyclerView
android:visibility="gone"
android:fillViewport="true"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:id="#+id/recyclerView_stationery_goods"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
and :
RecyclerView recycleView1 = (RecyclerView) findViewById(R.id.recyclerView_popular_goods);
RecyclerView recycleView2 = (RecyclerView) findViewById(R.id.recyclerView_competitive_goods);
RecyclerView recycleView3 = (RecyclerView) findViewById(R.id.recyclerView_stationery_goods);
recycleView1.setNestedScrollingEnabled(false);
recycleView2.setNestedScrollingEnabled(false);
recycleView3.setNestedScrollingEnabled(false);
If your devices API is below v 21, use the following:
ViewCompat.setNestedScrollingEnabled(recycleView1, false);
ViewCompat.setNestedScrollingEnabled(recycleView2, false);
ViewCompat.setNestedScrollingEnabled(recycleView3, false);
Your design needs to change. As soon as you're adding RecyclerView with nested scrolling disabled, you should keep in mind that view will have its items created all at once.
It basically means no typical RecyclerView optimization magic when only needed amount of items is created and rendered, then reused, based on screen real estate etc.
In your case the situation is even less good as you have 3 such RecyclerViews. The performance of your solution will of course depend on hardware and number of items inside each RecyclerView, but pls do consider using just ONE RecyclerView and no ScrollView at all.
Finally I achieved.I used NestedScrollView as root.And used only 1 recyclerview.And in adapter of this recyclerview I created other recyclerViews.Scrolling smooth Thanks #Venky
I have designed a layout with map fragment and recyclerView.
Each recyclerView item is cardview (I have specified give the xml layout).
The problem is RecyclerView item doesn't fill screen width.
img here
I tried to change layout_width to fill_parent, match_parent ... but it can't help
Here is the layout for each item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:id="#+id/cardView">
<LinearLayout
android:id="#+id/locationItemView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="120px"
android:layout_height="120px"
android:id="#+id/imgIcon"
android:background="#drawable/image_bg"
android:layout_margin="5dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true" />
<LinearLayout
android:id="#+id/layoutInfo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="#+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Location Name"
android:textColor="#d5c645"
android:textStyle="bold"
android:textSize="20dp"
android:padding="3dp" />
<TextView
android:id="#+id/txtAddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Location Address"
android:textSize="16dp"
android:padding="3dp" />
<TextView
android:id="#+id/txtDistance"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="Location Distance"
android:textSize="14dp"
android:textStyle="italic"
android:padding="2dp"
android:textAlignment="viewEnd" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
and the main_layout
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="0px" android:id="#+id/map" tools:context=".Main"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_weight=".6"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight=".4"
android:divider="#FEFFCC"
android:dividerHeight="1dp" />
</LinearLayout>
<ListView
android:id="#+id/navdrawer"
android:layout_width="250px"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="?attr/colorPrimaryDark"
android:choiceMode="singleChoice"
android:divider="#android:color/white"
android:dividerHeight="1dp"
android:drawSelectorOnTop="false"/>
</android.support.v4.widget.DrawerLayout>
Hope anyone can help me. I am stuck with it for 3 days.
Thank you.
====================================
Edit on 19/11/15
I don't thing the problem is my itemView layout because when I change it to GridLayout it still doesn't fill the width.
Here is my CustomAdapter for RecyclerView
public class LocationDetailsAdapter extends RecyclerView.Adapter<LocationDetailsViewHolder> {
Context _context;
ArrayList<LocationDetails> _data;
public LocationDetailsAdapter(Context _context, ArrayList<LocationDetails> _object) {
this._context = _context;
_data = _object;
}
#Override
public LocationDetailsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View _v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_location,null );
LocationDetailsViewHolder _viewHolder = new LocationDetailsViewHolder(_v);
return _viewHolder;
}
#Override
public void onBindViewHolder(LocationDetailsViewHolder locationDetailsViewHolder, int i) {
LocationDetails _location = _data.get(i);
locationDetailsViewHolder._imgType.setImageResource(R.drawable.repair_img);
locationDetailsViewHolder._locationName.setText(_location.get_locationName());
locationDetailsViewHolder._locationAddress.setText(_location.get_locationAddress() + ", " + _location.get_district() + ", " + _location.get_province());
locationDetailsViewHolder._distance.setText(String.valueOf(_location.get_distance()) + " km");
locationDetailsViewHolder._locationName.setOnClickListener(clickListener);
locationDetailsViewHolder._imgType.setOnClickListener(clickListener);
locationDetailsViewHolder._locationAddress.setOnClickListener(clickListener);
locationDetailsViewHolder._locationName.setTag(locationDetailsViewHolder);
locationDetailsViewHolder._imgType.setTag(locationDetailsViewHolder);
locationDetailsViewHolder._locationAddress.setTag(locationDetailsViewHolder);
}
#Override
public int getItemCount() {
return (null != _data ? _data.size() : 0);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
LocationDetailsViewHolder _holder = (LocationDetailsViewHolder)v.getTag();
int _pos = _holder.getPosition();
int _id = _data.get(_pos).get_id();
Intent _intent = new Intent(CommonFields._context, ItemView.class);
_intent.putExtra("LocationID",_id);
_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
CommonFields._context.startActivity(_intent);
}
};
}
and here I get RecylerView in main
_locationView = (RecyclerView)findViewById(R.id.locationList);
_locationView.setLayoutManager(new LinearLayoutManager(this));
_adapter = new LocationDetailsAdapter(Main.this, CommonFields._locationData);
_locationView.setAdapter(_adapter);
When inflating a View from a LayoutInflater, you need to pass a parent parameter in order for layout_* attributes to be used. That's because these attributes need to create the correct LayoutParams class. That means that you can't use inflate(R.layout.*, null), but must instead pass a ViewGroup for the second parameter. In most cases, you also want to use the three-parameter version of the method and pass false as the third parameter. If this is omitted or true then the View is immediately added to the parent, which causes problems in places like onCreateViewHolder() because the framework is designed to perform this operation later instead. For more details, see this answer.
In your case, you have the line
View _v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_location,null );
You should change it to
View _v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_location, viewGroup, false );
You should create View like this
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
// create a new view
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view, viewGroup, false);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
Maybe my answer has a different approach, but it works to occupy the entire width of the screen and not break the elements when passing through the recycling view.
Adapter adapterBalanceInquiry = new Adapter(getActivity(), list);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setAdapter(adapterBalanceInquiry);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false));
recyclerView.post(new Runnable() {
#Override
public void run() {
try {
int dx = (recyclerView.getWidth() - recyclerView.getChildAt(0).getWidth());
recyclerView.scrollBy(-dx, 0);
LinearSnapHelper snapHelper = new LinearSnapHelper();
recyclerView.setOnFlingListener(null);
snapHelper.attachToRecyclerView(recyclerView);
}catch (Exception e){
e.printStackTrace();
}
}
});
I create a cardview design with indicator in the left (Red, Green) but i have problem, how can i change the indicator color depends on the status from database. If the status say "No" then the indicator turn red and if "Yes" the indicator turn green.
This is the xml file :
<?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="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="6dp"
card_view:cardElevation="3dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.9">
<ImageView
android:layout_marginLeft="22dp"
android:layout_marginTop="14dp"
android:layout_marginBottom="14dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/rectangle"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.1"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_card_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txt_order_date"
android:textSize="13sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txt_customer_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txt_order_number"
android:textSize="12sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txt_product_status"
android:textSize="12sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txt_notes"
android:textSize="12sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:layout_weight="1"
android:maxLines="4"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#drawable/layout_bg"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
android:layout_below="#+id/layout_card_item"
android:gravity="center"
android:weightSum="1">
<Button
android:id="#+id/download_pdf"
android:textSize="14sp"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#e1e3e8"
android:focusable="false"
android:textColor="#000307"
android:focusableInTouchMode="true"
android:drawableLeft="#drawable/ic_pictogram_download_orange"
android:text=" Download PDF"
/>
<!--<ImageButton-->
<!--android:layout_width="10dp"-->
<!--android:layout_height="10dp"-->
<!--android:src="#mipmap/ic_order_download_pdf"/>-->
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
This is the adapter :
public class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.OrderListViewHolder> {
private ArrayList<OrderListModel> itemOrderList;
public OrderListAdapter(ArrayList<OrderListModel> itemOrderList) {
this.itemOrderList = itemOrderList;
}
#Override
public OrderListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.order_list_item, parent, false);
return new OrderListViewHolder(view);
}
#Override
public void onBindViewHolder(OrderListViewHolder orderListViewHolder, int position) {
orderListViewHolder.txtDate.setText(itemOrderList.get(position).getDate());
orderListViewHolder.txtOrderNumber.setText(itemOrderList.get(position).getOrderNumber());
orderListViewHolder.txtCustomerName.setText(itemOrderList.get(position).getCustomerName());
orderListViewHolder.txtProductStatus.setText(itemOrderList.get(position).getProductStatus());
orderListViewHolder.txtNotes.setText(itemOrderList.get(position).getNotes());
}
#Override
public int getItemCount() {
return (itemOrderList != null) ? itemOrderList.size() : 0;
// return itemOrderList.size();
}
public class OrderListViewHolder extends RecyclerView.ViewHolder{
private TextView txtDate, txtOrderNumber, txtCustomerName, txtProductStatus,
txtNotes;
public OrderListViewHolder(View itemView) {
super(itemView);
txtDate = (TextView) itemView.findViewById(R.id.txt_order_date);
txtOrderNumber = (TextView) itemView.findViewById(R.id.txt_order_number);
txtCustomerName = (TextView) itemView.findViewById(R.id.txt_customer_name);
txtProductStatus = (TextView) itemView.findViewById(R.id.txt_product_status);
txtNotes = (TextView) itemView.findViewById(R.id.txt_notes);
}
}
}
This is the main :
public class OrderListFragment extends Fragment {
private RecyclerView recyclerView;
private OrderListAdapter adapter;
private ArrayList<OrderListModel> OrderListArrayList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order_list, container, false);
getActivity().setTitle(R.string.title_mn_order_list);
addData();
recyclerView = (RecyclerView) view.findViewById(R.id.orderList_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new OrderListAdapter(OrderListArrayList);
recyclerView.setAdapter(adapter);
return view;
}
void addData(){
OrderListArrayList = new ArrayList<>();
OrderListArrayList.add(new OrderListModel(
"4 Juli 2018 10:54",
"0001",
"Jopa",
"No",
"Notes"));
OrderListArrayList.add(new OrderListModel(
"4 Juli 2018 10:54",
"0001",
"Jopa",
"Yes",
"Notes"));
}
}
Do you have any idea how can i change it?
You must give an id to your ImageView say status
In OrderListViewHolder add in your declarations private ImageView status;
In OrderListViewHolder add status = (ImageView) itemView.findViewById(R.id.status);
In OrderListViewHolder add
if (itemOrderList.get(position).getStatus().equals("Yes")) {
orderListViewHolder.status.setBackgroundColor(0x00ff00);
} else {
orderListViewHolder.status.setBackgroundColor(0xff0000); }
of course you must create the getStatus() method like all the others getSomething()
Assuming, that your ImageView is your indicator bar:
<ImageView
android:id="#+id/ivIndicator" <!-- Add this id -->
android:layout_marginLeft="22dp"
android:layout_marginTop="14dp"
android:layout_marginBottom="14dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/rectangle"/>
Get a reference to it in your OrderListViewHolder:
ivIndicator = (ImageView) itemView.findViewById(R.id.ivIndicator);
And then tint your imageview in onBindViewHolder:
if("Yes".equals(itemOrderList.get(position).getStatus())) {
orderListViewHolder.ivIndicator.setColorFilter(ContextCompat.getColor(activity, android.R.color.green))
else {
orderListViewHolder.ivIndicator.setColorFilter(ContextCompat.getColor(activity, android.R.color.red))
}
Make two drawable files like #drawable/rectangle, set it with different color you want.
if(status.equals("No") {
yourView.setBackground(context.getResources().getDrawable(R.drawable.rectangleWithRed));
}
else if (status.equals("Yes") {
yourView.setBackground(context.getResources().getDrawable(R.drawable.rectangleWithGreen);
}
if you want to change the color according to the status, then on onBindViewHolder of your Recycler Adapter, check for the status and set to desired color.
if(status.equals("Yes")
{
rectangleImageView.setColor(Color.GREEN);
}
else
{
rectangleImageView.setColor(Color.RED);
}
public void onBindViewHolder(OrderListViewHolder orderListViewHolder, int position) {
if (OrderListModel.getProductStatus().equals("Yes"))
rectangleImageView.setColorFilter(getContext().getResources().getColor(R.color.green));
} else {
rectangleImageView.setColorFilter(getContext().getResources().getColor(R.color.red));
}
}
Fragment has ViewPager, in ViewPager we are swiping between two fragments(let's name it sub-fragment). And first and second sub-fragment has got RecyclerView.
I doesn't know what's going on because I've create RecyclerView exactly in the same way in other fragment and It is workking well.
recycler_view_item: (I'm sure that this item is appriopriate and its ids are compatible with Adapter class
<?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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorHeaderText"
android:weightSum="100"
android:layout_marginBottom="4dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="20"
android:weightSum="50">
<TextView
android:text="Client"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:id="#+id/textView8"
android:layout_weight="15"
style="#style/ItemPaymentsHeaderTextView"
/>
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/clientinfo_item_client"
android:layout_weight="35"
style="#style/ItemPaymentsInfoTextView"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="25"
android:weightSum="50">
<TextView
android:text="Date"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:id="#+id/textView13"
android:layout_weight="15"
style="#style/ItemPaymentsHeaderTextView"
/>
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/clientinfo_item_date"
android:layout_weight="35"
style="#style/ItemPaymentsInfoTextView"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="27"
android:weightSum="50">
<TextView
android:text="Payment amount"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:id="#+id/textView9"
android:layout_weight="15"
style="#style/ItemPaymentsHeaderTextView"
/>
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/clientinfo_item_totalamount"
android:layout_weight="35"
style="#style/ItemPaymentsInfoTextView"/>
</LinearLayout>
<!--TODO jak bedzie po wszystkim to wyrzucic TYP ( określony w TabLayout)-->
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="20"
android:weightSum="50">
<TextView
android:text="Type"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:id="#+id/textView10"
android:layout_weight="15"
style="#style/ItemPaymentsHeaderTextView"
/>
<TextView
android:text="Purchase"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/clientinfo_item_type"
android:layout_weight="35"
style="#style/ItemPaymentsInfoTextView"/>
</LinearLayout>
<ImageButton
android:layout_width="0dp"
android:layout_height="wrap_content"
app:srcCompat="#drawable/arrow_expand_24"
android:id="#+id/clientinfo_item_downarrow"
android:background="#color/icon_transparent"
android:layout_weight="5"
android:scaleType="fitCenter"
android:elevation="0dp"
android:layout_gravity="center_vertical|clip_horizontal"/>
FrameLayout that contain ViewPager and TabLayout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.debtors.Fragments.FragmentSingleClientInfo">
<android.support.design.widget.TabLayout
android:id="#+id/clientsinfo_tabs"
style="#style/CategoryTab"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/clientsinfo_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
onCreateView - method where I create RecyclerView
listOfPayments that I am passing to AdapterClientInfo is not null.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
listOfPayments = getPaymentsByClientId(clientsID);
for( Payment p : listOfPayments ){
Log.i(TAG, "onCreateView: payment : " + p.toString(true));
}
View rootView = inflater.inflate(R.layout.recycler_view_with_viewpager,container, false);
AdapterClientInfo adapterClientInfo = new AdapterClientInfo(getContext(),listOfPayments);
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view_with_viewpager);
setupRecyclerView(recyclerView);
recyclerView.setAdapter(adapterClientInfo);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return rootView;
}
In above method I inflate layout.recycler_view_with_viewpager:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="55dp"
android:id="#+id/recycler_view_with_viewpager"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
And in AdapterClientInfo only constructor is calling while creating instance and any of other method doesn't work, nothing is called.
AdapterClientInfo:
public class AdapterClientInfo extends RecyclerView.Adapter<AdapterClientInfo.MyViewHolder> {
private static final String TAG = AdapterClientInfo.class.getSimpleName();
List<Payment> listOfPayments = new ArrayList<>();
Context context;
public AdapterClientInfo(Context context, List<Payment> list) {
Log.i(TAG, "AdapterClientInfo: ");
this.context = context;
this.listOfPayments = list;
Log.i(TAG, "AdapterClientInfo: size of list : " + list.size());
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder: ");
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_clients_info_payments, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.i(TAG, "onBindViewHolder: START");
Payment payment = listOfPayments.get(position);
Log.i(TAG, "onBindViewHolder: payment " + payment.toString());
String clientName = getClientByID(payment.getPaymentClientID()).getClientName();
String[] dateArray = payment.getPaymentDate().split(" ");
String dateString = dateArray[0];
holder.textViewClient.setText(clientName);
holder.textViewDate.setText(dateString);
holder.textViewPaymentAmount.setText(String.valueOf(payment.getPaymentAmount()));
if(payment.isPaymentGotOrGiven())//if tru
holder.textViewType.setText("Received");
else
holder.textViewType.setText("Given");
Log.i(TAG, "onBindViewHolder: END");
}
#Override
public int getItemCount() {
Log.i(TAG, "getItemCount: " + listOfPayments.size());
return listOfPayments.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewClient, textViewPaymentAmount, textViewDate, textViewType;
public MyViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "MyViewHolder: ");
textViewClient = (TextView) itemView.findViewById(R.id.clientinfo_item_client);
textViewPaymentAmount = (TextView) itemView.findViewById(R.id.clientinfo_item_totalamount);
textViewDate = (TextView) itemView.findViewById(R.id.clientinfo_item_date);
textViewType = (TextView) itemView.findViewById(R.id.clientinfo_item_type);
}
}
private Client getClientByID(long ID){
DatabaseClients dbClients = new DatabaseClients(context);
Client client = dbClients.getClientByID(ID);
return client;
}
}
I'm sure that listOfPayments's size is more than 0 so getItemCount return more than zero
Logs show that only Constructor is calling
I think that it is simple mistake but I can't notice that...
Problem was causing by method in ViewPagerAdapter. I don't know if it was autogenerated, I copied it accidentally or .. I don't know but deleting this method helped.
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
I have designed a layout with map fragment and recyclerView.
Each recyclerView item is cardview (I have specified give the xml layout).
The problem is RecyclerView item doesn't fill screen width.
img here
I tried to change layout_width to fill_parent, match_parent ... but it can't help
Here is the layout for each item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:id="#+id/cardView">
<LinearLayout
android:id="#+id/locationItemView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="120px"
android:layout_height="120px"
android:id="#+id/imgIcon"
android:background="#drawable/image_bg"
android:layout_margin="5dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true" />
<LinearLayout
android:id="#+id/layoutInfo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="#+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Location Name"
android:textColor="#d5c645"
android:textStyle="bold"
android:textSize="20dp"
android:padding="3dp" />
<TextView
android:id="#+id/txtAddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Location Address"
android:textSize="16dp"
android:padding="3dp" />
<TextView
android:id="#+id/txtDistance"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="Location Distance"
android:textSize="14dp"
android:textStyle="italic"
android:padding="2dp"
android:textAlignment="viewEnd" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
and the main_layout
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="0px" android:id="#+id/map" tools:context=".Main"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_weight=".6"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight=".4"
android:divider="#FEFFCC"
android:dividerHeight="1dp" />
</LinearLayout>
<ListView
android:id="#+id/navdrawer"
android:layout_width="250px"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="?attr/colorPrimaryDark"
android:choiceMode="singleChoice"
android:divider="#android:color/white"
android:dividerHeight="1dp"
android:drawSelectorOnTop="false"/>
</android.support.v4.widget.DrawerLayout>
Hope anyone can help me. I am stuck with it for 3 days.
Thank you.
====================================
Edit on 19/11/15
I don't thing the problem is my itemView layout because when I change it to GridLayout it still doesn't fill the width.
Here is my CustomAdapter for RecyclerView
public class LocationDetailsAdapter extends RecyclerView.Adapter<LocationDetailsViewHolder> {
Context _context;
ArrayList<LocationDetails> _data;
public LocationDetailsAdapter(Context _context, ArrayList<LocationDetails> _object) {
this._context = _context;
_data = _object;
}
#Override
public LocationDetailsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View _v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_location,null );
LocationDetailsViewHolder _viewHolder = new LocationDetailsViewHolder(_v);
return _viewHolder;
}
#Override
public void onBindViewHolder(LocationDetailsViewHolder locationDetailsViewHolder, int i) {
LocationDetails _location = _data.get(i);
locationDetailsViewHolder._imgType.setImageResource(R.drawable.repair_img);
locationDetailsViewHolder._locationName.setText(_location.get_locationName());
locationDetailsViewHolder._locationAddress.setText(_location.get_locationAddress() + ", " + _location.get_district() + ", " + _location.get_province());
locationDetailsViewHolder._distance.setText(String.valueOf(_location.get_distance()) + " km");
locationDetailsViewHolder._locationName.setOnClickListener(clickListener);
locationDetailsViewHolder._imgType.setOnClickListener(clickListener);
locationDetailsViewHolder._locationAddress.setOnClickListener(clickListener);
locationDetailsViewHolder._locationName.setTag(locationDetailsViewHolder);
locationDetailsViewHolder._imgType.setTag(locationDetailsViewHolder);
locationDetailsViewHolder._locationAddress.setTag(locationDetailsViewHolder);
}
#Override
public int getItemCount() {
return (null != _data ? _data.size() : 0);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
LocationDetailsViewHolder _holder = (LocationDetailsViewHolder)v.getTag();
int _pos = _holder.getPosition();
int _id = _data.get(_pos).get_id();
Intent _intent = new Intent(CommonFields._context, ItemView.class);
_intent.putExtra("LocationID",_id);
_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
CommonFields._context.startActivity(_intent);
}
};
}
and here I get RecylerView in main
_locationView = (RecyclerView)findViewById(R.id.locationList);
_locationView.setLayoutManager(new LinearLayoutManager(this));
_adapter = new LocationDetailsAdapter(Main.this, CommonFields._locationData);
_locationView.setAdapter(_adapter);
When inflating a View from a LayoutInflater, you need to pass a parent parameter in order for layout_* attributes to be used. That's because these attributes need to create the correct LayoutParams class. That means that you can't use inflate(R.layout.*, null), but must instead pass a ViewGroup for the second parameter. In most cases, you also want to use the three-parameter version of the method and pass false as the third parameter. If this is omitted or true then the View is immediately added to the parent, which causes problems in places like onCreateViewHolder() because the framework is designed to perform this operation later instead. For more details, see this answer.
In your case, you have the line
View _v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_location,null );
You should change it to
View _v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_location, viewGroup, false );
You should create View like this
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
// create a new view
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view, viewGroup, false);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
Maybe my answer has a different approach, but it works to occupy the entire width of the screen and not break the elements when passing through the recycling view.
Adapter adapterBalanceInquiry = new Adapter(getActivity(), list);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setAdapter(adapterBalanceInquiry);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false));
recyclerView.post(new Runnable() {
#Override
public void run() {
try {
int dx = (recyclerView.getWidth() - recyclerView.getChildAt(0).getWidth());
recyclerView.scrollBy(-dx, 0);
LinearSnapHelper snapHelper = new LinearSnapHelper();
recyclerView.setOnFlingListener(null);
snapHelper.attachToRecyclerView(recyclerView);
}catch (Exception e){
e.printStackTrace();
}
}
});