One of my app activity is called DayGallery activity (infinite images gallery) ,
when i open the gallery, it show first image randomly , and not start with first image i specified in DayGallery activity code .
what am trying to achieve is:
FIRST: start with first image specified in DayGallery activity code as below :
when open Day1 gallery ,first image to appear is:
R.drawable.day_one_1
and when open Day2 gallery ,first image to appear is:
R.drawable.day_two_1
and like that for all Days gallery, also keep infinite scrolling in both sides.
SECOND : if am in gallery stopped on image named day_one_7 for example then press back to go to previous activity and return again to gallery , i want to see the same image i saw before i left gallery ,
but if i exit the app then open the gallery again , it must reset to show the first image i specified in DayGallery activity code , explained as bellow image .
actually i searched google for that purpose but i cant get any helpful thing about it ,
any help will be highly appreciated .
DayGallery.java:
#SuppressWarnings("deprecation")
public class DayGallery extends Activity {
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// Set the layout to use
setContentView(R.layout.main);
if (customTitleSupported) {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);
tv = (TextView) findViewById(R.id.title_tv1);
tv.setTypeface(FontFactory.getBFantezy(getBaseContext()));
}
InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne);
galleryOne.setAdapter(initializeImages());
galleryOne.setSelection(galleryOne.getCount()/2);
}
private InfiniteGalleryAdapter initializeImages() {
InfiniteGalleryAdapter galleryAdapter = null;
String day = getIntent().getStringExtra("dayname");
if(day.equalsIgnoreCase("Day1")){
int[] tempimages = { R.drawable.day_one_1, R.drawable.day_one_2,R.drawable.day_one_3,
R.drawable.day_one_4, R.drawable.day_one_5,R.drawable.day_one_6,R.drawable.day_one_7,
R.drawable.day_one_8, R.drawable.day_one_9,R.drawable.day_one_10,R.drawable.day_one_11,
R.drawable.day_one_12
};
String[] name = { "00:35","00:35","00:35","1:07","2:00","2:01","2:09",
"2:12","2:15","6:13","6:13","6:13"
};
tv.setText("Day one pictures");
galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);
}
else if(day.equalsIgnoreCase("Day2")){
int[] tempimages = { R.drawable.day_two_1, R.drawable.day_two_2,R.drawable.day_two_3,
R.drawable.day_two_4, R.drawable.day_two_5,R.drawable.day_two_6,R.drawable.day_two_7,
R.drawable.day_two_8, R.drawable.day_two_9,R.drawable.day_two_10,R.drawable.day_two_11,
R.drawable.day_two_12
};
String[] name = { "12:04","12:04", "12:04","12:05","12:06", "12:07",
"12:07","12:07","12:08","12:10","12:10","12:10"
};
tv.setText("Day two pictures");
galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);
}
// AND THE SAME FOR REST OF DAYS TILL Day10//
return galleryAdapter;
}
}
class InfiniteGalleryAdapter extends BaseAdapter {
private Context mContext;
private int[] images;
private String[] name;
public InfiniteGalleryAdapter(Context c, int[] imageIds,String[] names) {
this.mContext = c;
images = imageIds;
name=names;
inflater = (LayoutInflater)mContext.getSystemService ( Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return Integer.MAX_VALUE;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
private LayoutInflater inflater=null;
public class ViewHolder{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = getImageView();
int itemPos = (position % images.length);
try { i.setImageResource(images[itemPos]); ((BitmapDrawable) i.getDrawable()).setAntiAlias(true);
}
catch (OutOfMemoryError e) { Log.e("InfiniteGalleryAdapter", "Out of memory creating imageview. Using empty view.", e);
}
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.gallery_items, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textView1);
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else holder=(ViewHolder)vi.getTag();
holder.text.setText(name[itemPos]);
final int stub_id=images[itemPos];
holder.image.setImageResource(stub_id);
return vi;
}
private ImageView getImageView() {
ImageView i = new ImageView(mContext);
return i;
}
}
#SuppressWarnings("deprecation")
class InfiniteGallery extends Gallery {
public InfiniteGallery(Context context) {
super(context);
init();
}
public InfiniteGallery(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public InfiniteGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
// These are just to make it look pretty
setSpacing(25);
setHorizontalFadingEdgeEnabled(false);
}
}
UPDATE:
I add this line of code :
galleryOne.setSelection(0);
after this line :
galleryOne.setSelection(galleryOne.getCount()/2);
in my code it result in showing the first image as specified it in DayGallery activity , but it result to one way infinite scrolling to left side only but not in both side ,
How we can get two way infinite scrolling of my gallery images with showing the first image as specified it in DayGallery activity ?
really appreciate any help , thanks.
I can tell you the logic to write infinite viewpager which uses fragments. This viewpager can scroll in both direction infinitely. Also it can be launched from any particular fragment. My requiremnet was:
I had an ebook and user can click on any menu(chapters) and it should launch that and then it should be possible to scroll both ways. I guess your are trying to achieve same thing with gallery:
Check the code:
InfinitePagerAdapter.java:
package com.example.multiplepages;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
/**
* A PagerAdapter that wraps around another PagerAdapter to handle paging
* wrap-around.
*
*/
public class InfinitePagerAdapter extends PagerAdapter {
private static final String TAG = "InfinitePagerAdapter";
private static final boolean DEBUG = true;
private PagerAdapter adapter;
public InfinitePagerAdapter(PagerAdapter adapter) {
this.adapter = adapter;
}
#Override
public int getCount() {
// warning: scrolling to very high values (1,000,000+) results in
// strange drawing behaviour
return Integer.MAX_VALUE;
}
/**
* #return the {#link #getCount()} result of the wrapped adapter
*/
public int getRealCount() {
return adapter.getCount();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
debug("getRealCount: " + getRealCount());
int virtualPosition = position % getRealCount();
debug("instantiateItem: real position: " + position);
debug("instantiateItem: virtual position: " + virtualPosition);
// only expose virtual position to the inner adapter
return adapter.instantiateItem(container, virtualPosition);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
int virtualPosition = position % getRealCount();
debug("destroyItem: real position: " + position);
debug("destroyItem: virtual position: " + virtualPosition);
// only expose virtual position to the inner adapter
adapter.destroyItem(container, virtualPosition, object);
}
/*
* Delegate rest of methods directly to the inner adapter.
*/
#Override
public void finishUpdate(ViewGroup container) {
adapter.finishUpdate(container);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return adapter.isViewFromObject(view, object);
}
#Override
public void restoreState(Parcelable bundle, ClassLoader classLoader) {
adapter.restoreState(bundle, classLoader);
}
#Override
public Parcelable saveState() {
return adapter.saveState();
}
#Override
public void startUpdate(ViewGroup container) {
adapter.startUpdate(container);
}
/*
* End delegation
*/
private void debug(String message) {
if (DEBUG) {
Log.d(TAG, message);
}
}
}
InfiniteViewPager.java:
package com.example.multiplepages;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
/**
* A {#link ViewPager} that allows pseudo-infinite paging with a wrap-around
* effect. Should be used with an {#link InfinitePagerAdapter}.
*
*/
public class InfiniteViewPager extends ViewPager {
int mPageOffset = 0;
public InfiniteViewPager(Context context) {
super(context);
}
public InfiniteViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setAdapter(PagerAdapter adapter) {
super.setAdapter(adapter);
// offset first element so that we can scroll to the left
setCurrentItem(0);
}
public void setpageOffset(int pageOffset) {
mPageOffset = pageOffset;
}
#Override
public void setCurrentItem(int item) {
// offset the current item to ensure there is space to scroll
item = getOffsetAmount() + (item % getAdapter().getCount());
item = item + mPageOffset;
super.setCurrentItem(item);
}
private int getOffsetAmount() {
if (getAdapter() instanceof InfinitePagerAdapter) {
InfinitePagerAdapter infAdapter = (InfinitePagerAdapter) getAdapter();
// allow for 100 back cycles from the beginning
// should be enough to create an illusion of infinity
// warning: scrolling to very high values (1,000,000+) results in
// strange drawing behaviour
return infAdapter.getRealCount() * 100;
} else {
return 0;
}
}
}
MultiplePageScroll.java : This is MainActivity
package com.example.multiplepages;
import java.util.ArrayList;
import java.util.List;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class MultiplePageScroll extends FragmentActivity {
private int listSize = 0;
public int listPos = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_multiple_page_scroll);
Bundle bundle = getIntent().getExtras();
listSize = bundle.getInt("listSize");
listPos = bundle.getInt("itemPosition");
PagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public int getCount() {
return listSize;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putInt("identifier", position);
fragment.setArguments(args);
return fragment;
}
};
// wrap pager to provide infinite paging with wrap-around
PagerAdapter wrappedAdapter = new InfinitePagerAdapter(adapter);
// actually an InfiniteViewPager
InfiniteViewPager viewPager = (InfiniteViewPager) findViewById(R.id.pager);
viewPager.setpageOffset(listPos);
viewPager.setAdapter(wrappedAdapter);
}
}
PageFragment.java:
package com.example.multiplepages;
import java.io.IOException;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
//import android.webkit.WebSettings;
import android.widget.Toast;
public class PageFragment extends Fragment {
String path="s_english/contents";
AssetManager assMan = null;
int pageIndex;
String pagePath = null;
String[] pageList = null;
private int listPosition;
public static PageFragment newInstance(int index) {
PageFragment pageFragment = new PageFragment();
Bundle bundle = new Bundle();
bundle.putInt("index", index);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
listPosition = args.getInt("identifier");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
WebView mWebView = (WebView) view.findViewById(R.id.webview);
mWebView.addJavascriptInterface(new JavaScriptInterface(getActivity()), "NativeFunc");
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.getSettings().setBuiltInZoomControls(true);
assMan = getActivity().getAssets();
try {
pageList = assMan.list(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pageIndex = listPosition;
pagePath=pageList[pageIndex];
mWebView.loadUrl("file:///android_asset/s_english/contents/" + pagePath);
//mWebView.loadUrl("http://192.168.0.33:8080/orginalsource/contents/" + pagePath);
//MultiplePageScroll.mSpinner.setVisibility(View.GONE);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("dummy", true);
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
}
}
activity_multiple_page_scroll.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.multiplepages.InfiniteViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
You can use sharedPrefernce to save the launchedpage and use that. By modifying this code a little you can achieve what you want.
Related
I am getting this error when doing intent. I don't know why it is coming. I need to go to the fragment to activity. I need to go to the next activity with the api in this application. I have tried many times and I am not getting the answer.**Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'**I have given the image below How to do fragment to activity intent i am new android devloper
package com.kannada.newspaper.india.utils;
import static com.kannada.newspaper.india.Constant.EXTRA_OBJC;
import static com.kannada.newspaper.india.Constant.getApiUrl;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.kannada.newspaper.india.AppConfig;
import com.kannada.newspaper.india.Constant;
import com.kannada.newspaper.india.MainActivity;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.ActivityCategoryDetail;
import com.kannada.newspaper.india.adapters.GalleryAdapter;
import com.kannada.newspaper.india.model.Category;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private Call<CallbackHome> callbackCall = null;
SharedPref sharedPref;
private View root_view;
public static final String EXTRA_OBJC = "key.EXTRA_OBJC";
private GalleryAdapter adapterCategory;
private GridView gridView;
private List<Category> mensWears;
private GalleryAdapter adapter;
private Category category;
public FragmentCategory() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
requestAction();
category = (Category) getActivity().getIntent().getSerializableExtra(Constant.EXTRA_OBJC);
// Inflate the layout for this fragment
root_view = inflater.inflate(R.layout.fragment_phones,container,false);
((TextView) root_view.findViewById(R.id.txt_title_category)).setText(getResources().getString(R.string.home_title_category));
return root_view;
}
private void requestAction() {
new Handler().postDelayed(this::requestHomeData, Constant.DELAY_TIME);
}
private void requestHomeData() {
this.callbackCall = RestAdapter.createAPI(getApiUrl).getHome(AppConfig.REST_API_KEY);
this.callbackCall.enqueue(new Callback<CallbackHome>() {
public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
CallbackHome responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
return;
}
displayData(responseHome);
}
public void onFailure(Call<CallbackHome> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
}
}
});
}
private void displayData(CallbackHome responseHome) {
displayCategory(responseHome.category);
}
private void displayCategory(List<Category> list) {
GridView gridView = (GridView) root_view.findViewById(R.id.gridHolder);
adapterCategory = new GalleryAdapter(getActivity(), list);
gridView.setAdapter(adapterCategory);
GalleryAdapter.setOnItemClickListener((v, obj, position) -> {
Intent intent = new Intent(getActivity(), ActivityCategoryDetail.class);
intent.putExtra(EXTRA_OBJC, obj);
startActivity(intent);
});
LinearLayout lyt_category = root_view.findViewById(R.id.lyt_category);
if (list.size() > 0) {
// lyt_category.setVisibility(View.VISIBLE);
} else {
// lyt_category.setVisibility(View.GONE);
}
}
}
GalleryAdapter adapter
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
public static void setOnItemClickListener(Object o) {
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
TextView prdId = view.findViewById(R.id.category_name);
ImageView imageView = view.findViewById(R.id.category_image);
// prdId.setText(prdId.toString());
Picasso.get()
.load(getApiUrl + "/upload/category/" + mensWears.get(i).category_image())
.placeholder(R.drawable.ic_thumbnail)
.into(imageView);
prdId.setText(mensWears.get(i).getItemName());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
You cannot put Object type in putExtra , it has to be either serailized, string, double and other primitive type.
You can do like this:
Category category = (Category)adapter.getItemAtPosition(pos);
or this should also work:
Category category = (Category) obj
then,
intent.putExtra(EXTRA_OBJC,category)
Note: Your Category class should implement parcelable or serilizable to be passed as an intent.
public class Category implements Serializable {
..........}
I am making a flash card app with SwipeCard
This is my FlashCardActivity:
import android.os.Bundle;
import android.text.style.TtsSpan;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.gson.Gson;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.adapter.CardListAdapter;
import org.koreanlab.fabloading.basickit.BasicCompatActivity;
import org.koreanlab.fabloading.basickit.remote.RemoteService;
import org.koreanlab.fabloading.basickit.remote.ServiceGenerator;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FlashCardActivity extends BasicCompatActivity {
private String TAG = getClass().getSimpleName();
private ArrayList<CardItem> cardList;
private ArrayAdapter<String> cardAdapter;
private CardListAdapter cardListAdapter;
private int i;
CardItem newCard;
#BindView(R.id.frame)
SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashcard);
ButterKnife.bind(this);
cardList = new ArrayList<>();
Log.d(TAG, "cardList created");
// get Two Words;
cardList.add(getCardItem());
cardList.add(getCardItem());
Log.d(TAG, "added Card");
cardListAdapter = new CardListAdapter(this, R.layout.card_item, cardList);
Log.d(TAG, "adapter created: " + (cardListAdapter == null ? "cardAdapter is NULL" : "cardAdapter is not NULL"));
flingContainer.setAdapter(cardListAdapter);
Log.d(TAG, "adapter set: " + (flingContainer == null ? "flingContainer is NULL" : "flingContainer is not NULL"));
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
cardList.remove(0);
cardListAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
makeToast(FlashCardActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(FlashCardActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
Log.d(TAG, "onAdapterAboutToEmpty: "+itemsInAdapter);
cardList.add(getCardItem());
cardListAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(FlashCardActivity.this, "Clicked!");
}
});
}
#OnClick(R.id.right)
public void right() {
/**
* Trigger the right event manually.
*/
flingContainer.getTopCardListener().selectRight();
}
#OnClick(R.id.left)
public void left() {
flingContainer.getTopCardListener().selectLeft();
}
public CardItem getCardItem() {
// No problem here.
return newCard;
}
}
Notice that, getCardItem() just get one card. First of all, it calls two cards and the cardList has two cards when activity has created. And after that I'd like to get just one card after swipe. getCardItem() has no problem. I can see that I receives the data from my Server.
This is my custom CardListAdapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import java.util.List;
public class CardListAdapter extends ArrayAdapter {
private final String TAG = this.getClass().getSimpleName();
private Context context;
private int cardResId;
private int frontResId;
private int backResId;
private List<CardItem> cardList;
private LayoutInflater mInflater;
//this, R.layout.card_item, R.id.card_front, R.id.card_back, cardList
public CardListAdapter(Context context, int cardResId, ArrayList<CardItem> cardList) {
super(context, cardResId);
this.context = context;
this.cardResId = cardResId;
this.cardList = cardList;
mInflater = LayoutInflater.from(context);
}
public void setItem(CardItem newItem) {
Log.d(TAG, "setItem");
for (int i = 0; i < cardList.size(); i++) {
CardItem item = cardList.get(i);
if (item.seq == newItem.seq) {
cardList.set(i, newItem);
break;
}
}
}
#Override
public int getCount() {
Log.d(TAG, "getVIew");
return 0;
}
public int getPosition(CardItem item) {
Log.d(TAG, "getPosition = "+item);
return cardList.indexOf(item);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(cardResId, parent,false);
holder = new ViewHolder();
Log.d(TAG, "getView");
holder.frontTV = convertView.findViewById(R.id.card_front);
holder.backTV = convertView.findViewById(R.id.card_back);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.frontTV.setText((String)getItem(position));
holder.backTV.setText((String)getItem(position));
return convertView;
}
static class ViewHolder
{
TextView frontTV, backTV;
}
}
I checked many blogs and other Q&A, but I haven't figured it out how to solve this problem. That activity keeps going back after receiving 'one word' data from the Server and It doesn't show any error messages.
I know there is lots of threads talk about first item problems in viewpager, I searched many time about my issue but no way I just lose time.
would you help me, please ?
I use FragmentStatePagerAdapter , fragment and loader manager that add radio buttons dynamically. the first iitem in view pager doesn't show radio buttons until I swipe to third item and back again to the first one.
screen
Image
Fragment:
package mohalim.android.egybankstest.Fragments;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import mohalim.android.egybankstest.Database.AppContract;
import mohalim.android.egybankstest.Models.Choice;
import mohalim.android.egybankstest.Models.Question;
import mohalim.android.egybankstest.R;
import mohalim.android.egybankstest.ResultActivity;
public class QuizFragement extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private static final String UPDATE = "update";
private static final int GET_CHOICES_LOADER_ID = 100;
private static final int UPDATE_CHOSEN_ANSWER_LOADER_ID = 101;
private static final String SELECTED_QUIZ = "selected_quiz";
ArrayList<Question> questions;
ArrayList<Choice> choices;
int questionPosition;
String selectedQuiz;
RadioGroup radioGroup;
TextView questionText;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
choices = new ArrayList<>();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.quiz_fragment, container, false);
questionText = view.findViewById(R.id.m);
radioGroup = view.findViewById(R.id.choices_radio);
radioGroup.removeAllViews();
questionText.setText(questions.get(questionPosition).getQuestion_text());
if (questionPosition == 0){
getActivity().getSupportLoaderManager()
.initLoader(GET_CHOICES_LOADER_ID,null,this)
.forceLoad();
}else {
getActivity().getSupportLoaderManager()
.restartLoader(GET_CHOICES_LOADER_ID,null,this)
.forceLoad();
}
/**
* end the session
*/
FloatingActionButton fab = view.findViewById(R.id.end_session);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ResultActivity.class);
intent.putExtra(SELECTED_QUIZ,selectedQuiz);
startActivity(intent);
getActivity().finish();
}
});
return view;
}
#NonNull
#Override
public Loader<Cursor> onCreateLoader(int id, #Nullable final Bundle args) {
if (id==GET_CHOICES_LOADER_ID){
Uri choicesUri = AppContract.ChoiceEntry.CONTENT_URI
.buildUpon()
.appendPath(String.valueOf(questions.get(questionPosition).getQuestionId()))
.build();
String questionId = String.valueOf(questions.get(questionPosition).getQuestionId());
String questionIDSelection = AppContract.ChoiceEntry.COLUMN_QUESTION_ID + "=?";
String[] questionIDSelectionArgs = new String[]{questionId};
return new CursorLoader(
getActivity(),
choicesUri,
null,
questionIDSelection,
questionIDSelectionArgs,
null
);
}else if(id == UPDATE_CHOSEN_ANSWER_LOADER_ID){
return new AsyncTaskLoader<Cursor>(getActivity()) {
#Nullable
#Override
public Cursor loadInBackground() {
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Uri updateChosenUri = AppContract.QuestionsEntry.CONTENT_URI
.buildUpon()
.appendPath(UPDATE)
.appendPath(String.valueOf(questions.get(questionPosition).getQuestionId())).build();
ContentValues contentValues = new ContentValues();
contentValues.put(AppContract.QuestionsEntry.COLUMN_ANSWER_CHOSEN,checkedId);
if (group.getChildAt(checkedId-1).getTag().toString().equals("1")){
contentValues.put(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT, 1);
}else if (group.getChildAt(checkedId-1).getTag().toString().equals("0")){
contentValues.put(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT, 0);
}
getActivity().getContentResolver().update(updateChosenUri,contentValues,null,null);
Cursor cursor = getActivity().getContentResolver().query(
AppContract.QuestionsEntry.CONTENT_URI.buildUpon().appendPath(String.valueOf(questions.get(questionPosition).getQuestionId())).build(),
null,null,null,null
);
if (cursor.getCount() == 1){
cursor.moveToFirst();
Log.v("string", cursor.getInt(cursor.getColumnIndex(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT))+"");
Log.v("string 2", group.getChildAt(radioGroup.getCheckedRadioButtonId()-1).getTag().toString());
}
}
});
return null;
}
};
}
return null;
}
#Override
public void onLoadFinished(#NonNull Loader<Cursor> loader, Cursor choicesCursor) {
if (questionPosition == 0){
Toast.makeText(getActivity(), ""+selectedQuiz, Toast.LENGTH_SHORT).show();
}
if (loader.getId() == GET_CHOICES_LOADER_ID){
if (choicesCursor.getCount() >0){
while (choicesCursor.moveToNext()){
String text = choicesCursor.getString(choicesCursor.getColumnIndex(AppContract.ChoiceEntry.COLUMN_CHOICE_TEXT));
int is_correct = choicesCursor.getInt(choicesCursor.getColumnIndex(AppContract.ChoiceEntry.COLUMN_IS_TRUE));
Choice choice = new Choice();
choice.setChoiceText(text);
choice.setCorrect(is_correct);
choices.add(choice);
}
for (int i=0; i<choices.size();i++){
LayoutInflater inflater = LayoutInflater.from(getContext());
final View radioButton = inflater.inflate(R.layout.radio_button,radioGroup,false);
((RadioButton) radioButton).setText(choices.get(i).getChoiceText());
radioButton.setTag(choices.get(i).isCorrect());
radioGroup.addView(radioButton);
}
for (int i = 0; i<radioGroup.getChildCount();i++){
radioGroup.getChildAt(i).setId(i+1);
}
}
if (questionPosition == 0){
getActivity().getSupportLoaderManager()
.initLoader(
UPDATE_CHOSEN_ANSWER_LOADER_ID,
null,
this).forceLoad();
}else {
getActivity().getSupportLoaderManager()
.restartLoader(
UPDATE_CHOSEN_ANSWER_LOADER_ID,
null,
this).forceLoad();
}
}
}
#Override
public void onLoaderReset(#NonNull Loader<Cursor> loader) {
}
public void setQuestions(ArrayList<Question> questions) {
this.questions = questions;
}
public void setQuestionPosition(int questionPosition) {
this.questionPosition = questionPosition;
}
public ArrayList<Question> getQuestions() {
return questions;
}
public int getQuestionPosition() {
return questionPosition;
}
public void setSelectedQuiz(String selectedQuiz) {
this.selectedQuiz = selectedQuiz;
}
}
ViewPagerAdapter
package mohalim.android.egybankstest.Adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import mohalim.android.egybankstest.Fragments.QuizFragement;
import mohalim.android.egybankstest.Models.Question;
public class MyQuizPager extends FragmentStatePagerAdapter {
ArrayList<Question> questions;
String selectedQuiz;
public MyQuizPager(FragmentManager fm, ArrayList<Question> questions, String selectedQuiz) {
super(fm);
this.questions = questions;
this.selectedQuiz = selectedQuiz;
}
#Override
public Fragment getItem(int position) {
QuizFragement fragment = new QuizFragement();
fragment.setQuestions(questions);
fragment.setQuestionPosition(position);
fragment.setSelectedQuiz(selectedQuiz);
return fragment;
}
#Override
public int getCount() {
return questions.size();
}
#Override
public int getItemPosition(Object object) {
QuizFragement fragment = (QuizFragement) object;
int position = fragment.getQuestionPosition();
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
}
}
All code is here
Finnaly I found the solution:
Quate:
By default it is viewpager.setOffscreenPageLimit(1) , meaning View
pager will by default load atleast 1 on the right and one on the left
tab of current tab.
https://stackoverflow.com/a/47054077/5862361
when i start quizActivity viewpager load the first item and the second too so the loadermanager restart before complete its work.
I solved it by adding another loadermanger
one for the first item and the second for the second one:
if (questionPosition == 0){
if (getActivity().getSupportLoaderManager() == null){
getActivity().getSupportLoaderManager().initLoader(
GET_CHOICES_LOADER_ID_FIRST,
null,
this
).forceLoad();
}else{
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID_FIRST,
null,
this
).forceLoad();
}
}else if (questionPosition == 1){
if (getActivity().getSupportLoaderManager() == null){
getActivity().getSupportLoaderManager().initLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}else {
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}
}else {
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}
In my App I have a RecyclerView connected with an adapter but everytime my device changes from landscape to portrait or something else, the view get reloaded and I'll get to the top again. I want to save my scroll position to the last item I saw.
Here is what I tried:
I have a Fragment that extends from another fragment the state should be save within the MainPageFragment. I tried to save the last position loaded and put it into the savedState, it gets correctly retrieved but If I call "scrollToPosition" nothing happens.
package com.pr0.pr0grammreloaded.fragment;
/**
* Created by Dominik on 22.02.2015.
*/
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.pr0.pr0grammreloaded.MainActivity;
import com.pr0.pr0grammreloaded.R;
import com.pr0.pr0grammreloaded.config.FilterConfig;
import com.pr0.pr0grammreloaded.util.FixedRecyclerView;
import com.pr0.pr0grammreloaded.util.MainPageSaveParcelable;
import com.pr0.pr0grammreloaded.util.MyLayoutManager;
import com.pr0.pr0grammreloaded.util.RecyclerViewDelegate;
import java.util.ArrayList;
import uk.co.senab.actionbarpulltorefresh.extras.actionbarsherlock.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import uk.co.senab.actionbarpulltorefresh.library.viewdelegates.AbsListViewDelegate;
/**
* Created by Dominik on 17.01.2015.
*/
public class MainPageFragment extends Pr0MainPageFragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static MainPageFragment newInstance(FilterConfig config) {
MainPageFragment fragment = new MainPageFragment();
fragment.config = config;
return fragment;
}
public MainPageFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(savedInstanceState != null){
MainPageSaveParcelable saveParcelable = savedInstanceState.getParcelable("save");
View rootView = inflater.inflate(R.layout.mainpage_fragment, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.list);
adapter = new ItemAdapter();
itemList = saveParcelable.itemList;
config = saveParcelable.config;
// use better layout manager, maybe write our own?
recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.getActivity(), 3));
recyclerView.setAdapter(adapter);
restorePositon = saveParcelable.position;
mPullToRefreshLayout = (PullToRefreshLayout) rootView.findViewById(R.id.ptr_layout);
// Now setup the PullToRefreshLayout
ActionBarPullToRefresh.from(getActivity())
// Mark All Children as pullable
.allChildrenArePullable()
// Set a OnRefreshListener
.listener(new OnRefreshListener() {
#Override
public void onRefreshStarted(View view) {
if (!isBlocked()) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, MainPageFragment.newInstance(MainActivity.filterConfig))
.commit();
}
}
})
// Finally commit the setup to our PullToRefreshLayout
.useViewDelegate(FixedRecyclerView.class, new RecyclerViewDelegate())
.setup(mPullToRefreshLayout);
loadFeed();
// recyclerView.scrollToPosition(saveParcelable.);
return rootView;
}else {
View rootView = inflater.inflate(R.layout.mainpage_fragment, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.list);
adapter = new ItemAdapter();
itemList = new ArrayList<>();
// use better layout manager, maybe write our own?
recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.getActivity(), 3));
recyclerView.setAdapter(adapter);
mPullToRefreshLayout = (PullToRefreshLayout) rootView.findViewById(R.id.ptr_layout);
// Now setup the PullToRefreshLayout
ActionBarPullToRefresh.from(getActivity())
// Mark All Children as pullable
.allChildrenArePullable()
// Set a OnRefreshListener
.listener(new OnRefreshListener() {
#Override
public void onRefreshStarted(View view) {
if (!isBlocked()) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, MainPageFragment.newInstance(MainActivity.filterConfig))
.commit();
}
}
})
// Finally commit the setup to our PullToRefreshLayout
.useViewDelegate(FixedRecyclerView.class, new RecyclerViewDelegate())
.setup(mPullToRefreshLayout);
loadFeed();
return rootView;
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onSaveInstanceState(Bundle state){
super.onSaveInstanceState(state);
restorePositon = lastPositon;
MainPageSaveParcelable saveParcelable = new MainPageSaveParcelable(itemList,firstChunk,config,restorePositon);
state.putParcelable("save",saveParcelable);
}
}
Pr0MainPageFragment
package com.pr0.pr0grammreloaded.fragment;
import android.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pr0.pr0grammreloaded.MainActivity;
import com.pr0.pr0grammreloaded.R;
import com.pr0.pr0grammreloaded.api.Api;
import com.pr0.pr0grammreloaded.api.Feed;
import com.pr0.pr0grammreloaded.api.InstantDeserializer;
import com.pr0.pr0grammreloaded.config.FilterConfig;
import com.squareup.picasso.Picasso;
import org.joda.time.Instant;
import java.util.ArrayList;
import java.util.List;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
import rx.functions.Action1;
import uk.co.senab.actionbarpulltorefresh.extras.actionbarsherlock.PullToRefreshLayout;
import static rx.android.observables.AndroidObservable.bindActivity;
/**
* Created by Dominik on 22.02.2015.
*/
public class Pr0MainPageFragment extends Fragment {
protected ItemAdapter adapter;
protected boolean firstChunk = true;
protected List<Feed.Item> itemList;
protected FilterConfig config;
private boolean blockLoading = false;
protected PullToRefreshLayout mPullToRefreshLayout;
protected int restorePositon = 0;
protected int lastPositon = 0;
protected RecyclerView recyclerView;
protected boolean isRestore = false;
/**
* Loads the feed from pr0gramm. This should be put into some kind of service
* that is injected into our activities.
*/
protected void loadFeed() {
if(!blockLoading) {
blockLoading = true;
Log.e("Pr0","Blocked loading!");
Gson gson = new GsonBuilder()
.registerTypeAdapter(Instant.class, new InstantDeserializer())
.create();
Api api = new RestAdapter.Builder()
.setEndpoint("http://pr0gramm.com")
.setConverter(new GsonConverter(gson))
.setLogLevel(RestAdapter.LogLevel.BASIC)
.build()
.create(Api.class);
// perform api request in the background and call
// back to the main thread on finish
if (firstChunk) {
bindActivity(MainActivity.getActivity(), api.itemsGet(config.getFlag(), 1)).subscribe(new Action1<Feed>() {
#Override
public void call(Feed feed) {
// we are now back in the main thread
firstChunk = false;
handleFeedResponse(feed);
}
});
} else {
//Log.e("Pr0", "Loading after ID : " + itemList.get(0).getId());
for(int x = 0; x < itemList.size();x ++){
Log.e("Pr0", "POS: " + x + ", ID : " + itemList.get(x).getId());
}
bindActivity(MainActivity.getActivity(), api.olderGet(itemList.get(itemList.size() - 1).getPromoted(), config.getFlag(), 1)).subscribe(new Action1<Feed>() {
#Override
public void call(Feed feed) {
// we are now back in the main thread
handleFeedResponse(feed);
}
});
}
}
}
/**
* Display the elements from the feed
*
* #param feed The feed to display
*/
private void handleFeedResponse(Feed feed) {
// display feed now.
//Log.i("MainActivity", "Number of items: " + feed.getItems().size());
adapter.addItems(feed.getItems());
mPullToRefreshLayout.setRefreshComplete();
restorePostion();
}
protected class ItemAdapter extends RecyclerView.Adapter<ItemView> {
ItemAdapter() {
setHasStableIds(true);
}
#Override
public ItemView onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.getActivity());
View view = inflater.inflate(R.layout.item_view, viewGroup, false);
return new ItemView(view);
}
#Override
public void onBindViewHolder(ItemView itemView, int i) {
// Log.e("Pr0","load id : " + i);
//Log.e("Pr0",String.valueOf(itemList.get(i).getId()));
String url = "http://thumb.pr0gramm.com/" + itemList.get(i).getThumb();
Picasso.with(getActivity())
.setIndicatorsEnabled(true);
Picasso.with(getActivity())
.load(url)
.into(itemView.image);
lastPositon = i;
Log.w("Pr0","last positon : " + i);
if(i > itemList.size() - 5){
//Log.e("Pr0","SIZE : " + itemList.size());
//Log.e("Pr0","End Reached Load After ID : " + itemList.get(0).getId());
loadFeed();
}
}
#Override
public int getItemCount() {
return itemList.size();
}
public void addItems(List<Feed.Item> itemsToAdd) {
int oldCount = itemList.size();
itemList.addAll(itemsToAdd);
notifyItemRangeInserted(oldCount, itemList.size());
/*
for(Feed.Item item : itemsToAdd) {
//Log.e("Pr0","Added image ID : " + item.getId());
int oldCount = itemList.size();
itemList.add(item);
notifyItemRangeInserted(oldCount, itemList.size());
}
*/
blockLoading = false;
Log.e("Pr0","Unblocked Loading");
//
}
#Override
public long getItemId(int position) {
return itemList.get(position).getId();
}
}
/**
* View holder for a view in the list of items
*/
private class ItemView extends RecyclerView.ViewHolder {
final ImageView image;
public ItemView(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
public boolean isBlocked(){
return this.blockLoading;
}
public void reset(){
itemList.clear();
firstChunk = true;
}
public void restorePostion(){
Log.w("Pr0", "Restore : " + restorePositon);
recyclerView.scrollToPosition(restorePositon);
}
}
And here is my Parcelable
package com.pr0.pr0grammreloaded.util;
import android.os.Parcel;
import android.os.Parcelable;
import com.pr0.pr0grammreloaded.account.User;
import com.pr0.pr0grammreloaded.api.Feed;
import com.pr0.pr0grammreloaded.config.FilterConfig;
import java.util.List;
/**
* Created by Dominik on 27.02.2015.
*/
public class MainPageSaveParcelable implements Parcelable{
public boolean firstChunk;
public List<Feed.Item> itemList;
public FilterConfig config;
public int position;
public MainPageSaveParcelable(List<Feed.Item> itemList, boolean firstChunk, FilterConfig config, int position){
this.firstChunk = firstChunk;
this.itemList = itemList;
this.config = config;
this.position = position;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(itemList);
dest.writeValue(config);
dest.writeValue(firstChunk);
dest.writeInt(position);
}
/** Static field used to regenerate object, individually or as arrays */
public static final Parcelable.Creator<MainPageSaveParcelable> CREATOR = new Parcelable.Creator<MainPageSaveParcelable>() {
public MainPageSaveParcelable createFromParcel(Parcel pc) {
return new MainPageSaveParcelable(pc);
}
public MainPageSaveParcelable[] newArray(int size) {
return new MainPageSaveParcelable[size];
}
};
/**Ctor from Parcel, reads back fields IN THE ORDER they were written */
public MainPageSaveParcelable(Parcel pc){
pc.readList(itemList,List.class.getClassLoader());
config = (FilterConfig) pc.readValue(FilterConfig.class.getClassLoader());
firstChunk = (boolean) pc.readValue(Boolean.class.getClassLoader());
position = pc.readInt();
}
}
you can use scroll listener and save first items or RecyclerView state on scrolling in SharedPreference or whatever you prefer
define these variables as private variables in your activity or fragment
int firstCompleteVisibleItemPosition;
int firstVisibleItemPosition;
Parcelable recyclerViewState;
use recyclerview on scroll listener
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
firstCompleteVisibleItemPosition = recyclerView.getLayoutManager().findFirstCompletelyVisibleItemPosition();
firstVisibleItemPosition = recyclerView.getLayoutManager().findFirstVisibleItemPosition();
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
}
});
and if orientation changes you can start your recyclerview by last position u saved by this method
linearLayoutManager.scrollToPositionWithOffset(firstVisibleItemPosition, 0);
or by last state of recyclerview
rv.getLayoutManager().onRestoreInstanceState(recyclerViewState);
i want to put a 2 column listview in the 2nd column of my first 2 column listview but i dont know how to and is it possible to use the same code to make it a 3 column list view?where in the first column is an image and the 2nd and 3rd column are both text i tried it but it has error... my code goes like this..
main
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class WeatherToday extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weathertoday);
ListView view = (ListView) findViewById(R.id.todaylist);
final List<MyStringPair> myStringPairList = MyStringPair.makeData(10);
MyStringPairAdapter adapter = new MyStringPairAdapter(this, myStringPairList);
view.setAdapter(adapter);
}
}
stringpairlist
import java.util.ArrayList;
import java.util.List;
public class MyStringPair {
private String columnOne;
private String columnTwo;
public MyStringPair(String columnOne, String columnTwo) {
super();
this.columnOne = columnOne;
this.columnTwo = columnTwo;
}
public String getColumnOne() {
return columnOne;
}
public void setColumnOne(String columnOne) {
this.columnOne = columnOne;
}
public String getColumnTwo() {
return columnTwo;
}
public void setColumnTwo(String columnTwo) {
this.columnTwo = columnTwo;
}
public static List<MyStringPair> makeData(int n) {
List<MyStringPair> pair = new ArrayList<MyStringPair>();
pair.add(new MyStringPair("Weather Condition", "Partly Cloudy"));
pair.add(new MyStringPair("Temperature", "30 Celcius "));
pair.add(new MyStringPair("Moisture", "Dew Point:" ));
pair.add(new MyStringPair("Wind", "Column2 "));
pair.add(new MyStringPair("Precipitation", "Column2 "));
pair.add(new MyStringPair("Condition", "Pressure:1014 mb "));
return pair;
}
}
adapter
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyStringPairAdapter extends BaseAdapter {
private Activity activity;
private List<MyStringPair> stringPairList;
public MyStringPairAdapter(Activity activity, List<MyStringPair> stringPairList) {
super();
this.activity = activity;
this.stringPairList = stringPairList;
}
#Override
public int getCount() {
return stringPairList.size();
}
#Override
public Object getItem(int position) {
return stringPairList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(R.layout.listrow, null);
}
TextView col1 = (TextView) convertView.findViewById(R.id.column1);
TextView col2 = (TextView) convertView.findViewById(R.id.column2);
col1.setText(stringPairList.get(position).getColumnOne());
col2.setText(stringPairList.get(position).getColumnTwo());
return convertView;
}
}
i've added a box on the column where i want another 2 column..basically i want to put two more column in the smaller box i want to divide the text into two parts so i need two columns for that but im out of ideas