I am using viewpager in my application and i want to make only one view Swipeable . Is it possible to do so.
I don't want the buttons at the bottom move when i swipe i only want the textview to change.
Any way can anyone help i searched a lot but couldn't find anything.
Here is my code.
There is a lot of code i can't paste all of it here.
Here is the link to the rest of it.
ViewPagerAdapter.java
public class ViewPagerAdapter extends PagerAdapter {
private Activity activity;
private Cursor cursor;
private int i = 0;
private int f = 0;
OnItemClickListener mOnItemClickListener;
public ViewPagerAdapter(Activity activity, Cursor cursor) {
this.activity = activity;
this.cursor = cursor;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
#Override
public int getCount() {
return cursor.getCount();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup container, final int position) {
final Context context = container.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.quote_detail_viewpager, container, false);
final TextView tvQuotes;
final ImageButton favouriteBtn, shareBtn, copyBtn, bgBtn, fontBtn;
tvQuotes = v.findViewById(R.id.vp_quotes);
favouriteBtn = v.findViewById(R.id.vp_fav);
shareBtn = v.findViewById(R.id.vp_share);
copyBtn = v.findViewById(R.id.vp_copy);
bgBtn = v.findViewById(R.id.vp_bg);
fontBtn = v.findViewById(R.id.vp_font);
int[] fonts = {
R.font.architects_daughter, R.font.artifika, R.font.carter_one,
R.font.expletus_sans, R.font.fredoka_one, R.font.graduate, R.font.jose,
R.font.magnolia, R.font.oswald, R.font.quicksand_bold, R.font.righteous,
R.font.salsa, R.font.schoolbell, R.font.sofadi_one
};
cursor.moveToPosition(position);
String id = cursor.getString(0);
String quote = cursor.getString(1);
String author = cursor.getString(2);
String text = quote + "\n \n - "+ author;
if (new DatabaseHelper(context).isFavourite(id)) {
favouriteBtn.setImageResource(R.drawable.ic_favorite);
}
tvQuotes.setText(text);
tvQuotes.setTypeface(PrefUtils.getTypefaceFromPrefs(context));
favouriteBtn.setOnClickListener(view ->
UtilsHelper.addOrDeleteFavourite(context, favouriteBtn, id, quote, author));
shareBtn.setOnClickListener(view -> UtilsHelper.shareTextIntent(context, text));
copyBtn.setOnClickListener(view -> UtilsHelper.copyText(context, text));
bgBtn.setOnClickListener(view -> mOnItemClickListener.onItemClick(view));
fontBtn.setOnClickListener(view -> {
int j = f++;
if (j < fonts.length) {
PrefUtils.setTypefaceFromPrefs(context, fonts[j]);
tvQuotes.setTypeface(PrefUtils.getTypefaceFromPrefs(context));
notifyDataSetChanged();
}
if (f == fonts.length) {
f = 0;
}
});
container.addView(v);
return v;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public void destroyItem(ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
public interface OnItemClickListener {
void onItemClick(View view);
}
}
DetailActivity.java
public class QuoteDetailActivity extends AppCompatActivity {
// Max swipe ad interval
private final int MAX_AD_COUNT = 10;
// count swipes
private int SWIPE_COUNT = 0;
// Min swipe ad interval
private int MIN_AD_COUNT = 6;
private int i = 0;
private InterstitialAd mInterstitialAd;
ViewPagerAdapter pagerAdapter;
RelativeLayout rootLayout;
int[] backgrounds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
Objects.requireNonNull(getSupportActionBar()).hide(); //hide the title bar
setContentView(R.layout.activity_quote_detail);
showInterstitialAd();
// String extras
String incomingActivity = getIntent().getStringExtra(Constants.STRING_EXTRA_INCOMING_ACTIVITY);
int position = getIntent().getIntExtra(Constants.STRING_EXTRA_ADAPTER_POSITION, 0);
DatabaseHelper mDBHelper = new DatabaseHelper(this);
ViewPager viewPager = findViewById(R.id.single_quote_viewpager);
backgrounds = BackgroundUtils.getAllBackgrounds();
rootLayout = findViewById(R.id.root_container);
rootLayout.setBackgroundResource(BackgroundUtils.getBackground(position));
FrameLayout adContainerView = findViewById(R.id.ad_view_container);
adContainerView.post(() ->
AdHelper.loadBanner(this, adContainerView, viewPager));
assert incomingActivity != null;
if (incomingActivity.contains(Constants.ACTIVITY_QUOTES)) {
pagerAdapter = new ViewPagerAdapter(this, mDBHelper.getAllQuotes());
} else if (incomingActivity.contains(Constants.ACTIVITY_FAVOURITE)) {
pagerAdapter = new ViewPagerAdapter(this, mDBHelper.getFavourites());
}
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(position); // Setup recycleView Item position
pagerAdapter.setOnItemClickListener(new ViewPagerAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view) {
changeBackground();
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
int count = SWIPE_COUNT++;
if (count >= MIN_AD_COUNT) {
if (mInterstitialAd != null) {
mInterstitialAd.show(QuoteDetailActivity.this);
SWIPE_COUNT = 0;
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void changeBackground() {
int j = i++;
if (j < backgrounds.length) {
rootLayout.setBackgroundResource(backgrounds[j]);
}
if (i == backgrounds.length) {
i = 0;
}
}
private void showInterstitialAd() {
MobileAds.initialize(this, initializationStatus -> {
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this, getString(R.string.interstitial_ad_unit),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
if (MIN_AD_COUNT < MAX_AD_COUNT) {
MIN_AD_COUNT++;
}
}
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
// Make sure to set your reference to null so you don't
// show it a second time.
mInterstitialAd = null;
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
mInterstitialAd = null;
}
});
}
}
Sure, something like the below pseudo_xml
<Parent View> -- background set to image
<ViewPager> -- only this part is swipable
<View Containing Buttons Fixed To The Bottom Of Parent/>
</Parent View>
Related
Hi all I am now integrating youtube API in my app where I have to parse the list of video id's from API then I have to show the videos in a list view when we click on it the video has to be played Until this works fine
There after when the user selects the full-screen mode that is landscape mode I get some errors
public final class VideoGallery extends Fragment implements OnFullscreenListener {
public static Context context;
public static final int ANIMATION_DURATION_MILLIS = 300;
public static final int LANDSCAPE_VIDEO_PADDING_DP = 5;
public final int RECOVERY_DIALOG_REQUEST = 1;
public static VideoListFragment listFragment;
public static VideoFragment videoFragment;
View videoBox;
View view;
View closeButton;
boolean isFullscreen;
public static YouTubePlayer.OnFullscreenListener onFullscreenListener;
static boolean back = false;
FrameLayout relativeLayout;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
onFullscreenListener = this;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
relativeLayout = new FrameLayout(getActivity());
inflater.inflate(R.layout.video_list_demo, relativeLayout, true);
MainActivity.headerText.setText("Video Gallery");
listFragment = (VideoGallery.VideoListFragment) getChildFragmentManager().findFragmentById(R.id.list_fragment);
videoFragment = (VideoGallery.VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
videoBox = relativeLayout.findViewById(R.id.video_box);
closeButton = relativeLayout.findViewById(R.id.close_button);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listFragment.getListView().clearChoices();
listFragment.getListView().requestLayout();
videoFragment.pause();
ViewPropertyAnimator animator = videoBox.animate()
.translationYBy(videoBox.getHeight())
.setDuration(ANIMATION_DURATION_MILLIS);
runOnAnimationEnd(animator, new Runnable() {
#Override
public void run() {
videoBox.setVisibility(View.INVISIBLE);
}
});
}
});
videoBox.setVisibility(View.INVISIBLE);
layout();
checkYouTubeApi();
return relativeLayout;
}
private void checkYouTubeApi() {
YouTubeInitializationResult errorReason =
YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(context);
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST).show();
} else if (errorReason != YouTubeInitializationResult.SUCCESS) {
String errorMessage =
String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Recreate the activity if user performed a recovery action
getActivity().recreate();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
layout();
}
#Override
public void onFullscreen(boolean isFullscreen) {
this.isFullscreen = isFullscreen;
layout();
}
private void layout() {
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
listFragment.getView().setVisibility(isFullscreen ? View.GONE : View.VISIBLE);
listFragment.setLabelVisibility(isPortrait);
closeButton.setVisibility(isPortrait ? View.VISIBLE : View.GONE);
if (isFullscreen) {
videoBox.setTranslationY(0); // Reset any translation that was applied in portrait.
setLayoutSize(videoFragment.getView(), MATCH_PARENT, MATCH_PARENT);
setLayoutSizeAndGravity(videoBox, MATCH_PARENT, MATCH_PARENT, Gravity.TOP | Gravity.LEFT);
} else if (isPortrait) {
setLayoutSize(listFragment.getView(), MATCH_PARENT, MATCH_PARENT);
setLayoutSize(videoFragment.getView(), MATCH_PARENT, WRAP_CONTENT);
setLayoutSizeAndGravity(videoBox, MATCH_PARENT, WRAP_CONTENT, Gravity.BOTTOM);
} else {
videoBox.setTranslationY(0); // Reset any translation that was applied in portrait.
int screenWidth = dpToPx(getResources().getConfiguration().screenWidthDp);
setLayoutSize(listFragment.getView(), screenWidth / 4, MATCH_PARENT);
int videoWidth = screenWidth - screenWidth / 4;
setLayoutSize(videoFragment.getView(), videoWidth, WRAP_CONTENT);
setLayoutSizeAndGravity(videoBox, videoWidth, WRAP_CONTENT,
Gravity.RIGHT | Gravity.CENTER_VERTICAL);
}
}
#TargetApi(16)
private void runOnAnimationEnd(ViewPropertyAnimator animator, final Runnable runnable) {
if (Build.VERSION.SDK_INT >= 16) {
animator.withEndAction(runnable);
} else {
animator.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
runnable.run();
}
});
}
}
public static final class VideoListFragment extends ListFragment {
private static List<VideoEntry> VIDEO_LIST;
private PageAdapter adapter;
private View videoBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callApi();
}
private void callApi() {
new DoGet(this, "videogallery").execute(WebserviceEndpoints.VIDEO_GALLERY);
}
public void handleVideoGalleryResponse(String response) {
try {
List<VideoEntry> list = new ArrayList<VideoEntry>();
if (response.length() > 0) {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.optJSONArray("items");
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.optJSONObject(i);
JSONObject obj = data.optJSONObject("id");
JSONObject obj1 = data.optJSONObject("snippet");
String videoId = obj.optString("videoId");
String videoTitle = obj1.getString("title");
if (!videoId.equals("")) {
list.add(new VideoEntry(videoTitle, videoId));
}
}
VIDEO_LIST = Collections.unmodifiableList(list);
adapter = new PageAdapter(getActivity(), VIDEO_LIST);
setListAdapter(adapter);
}
} catch (Exception e) {
Log.d("", "handleResponse: ", e);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
videoBox = getActivity().findViewById(R.id.video_box);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String videoId = VIDEO_LIST.get(position).videoId;
back = false;
VideoFragment videoFragment = (VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
videoFragment.setVideoId(videoId);
if (videoBox.getVisibility() != View.VISIBLE) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
videoBox.setTranslationY(videoBox.getHeight());
}
videoBox.setVisibility(View.VISIBLE);
}
if (videoBox.getTranslationY() > 0) {
videoBox.animate().translationY(0).setDuration(ANIMATION_DURATION_MILLIS);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
VideoFragment f = (VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
if (f != null)
getActivity().getFragmentManager().beginTransaction().remove(f).commit();
if (adapter != null)
adapter.releaseLoaders();
}
public void setLabelVisibility(boolean visible) {
if (adapter != null)
adapter.setLabelVisibility(visible);
}
}
private static final class PageAdapter extends BaseAdapter {
private final List<VideoEntry> entries;
private final List<View> entryViews;
private final Map<YouTubeThumbnailView, YouTubeThumbnailLoader> thumbnailViewToLoaderMap;
private final LayoutInflater inflater;
private final ThumbnailListener thumbnailListener;
private boolean labelsVisible;
public PageAdapter(Context context, List<VideoEntry> entries) {
this.entries = entries;
entryViews = new ArrayList<View>();
thumbnailViewToLoaderMap = new HashMap<YouTubeThumbnailView, YouTubeThumbnailLoader>();
inflater = LayoutInflater.from(context);
thumbnailListener = new ThumbnailListener();
labelsVisible = true;
}
public void releaseLoaders() {
for (YouTubeThumbnailLoader loader : thumbnailViewToLoaderMap.values()) {
loader.release();
}
}
public void setLabelVisibility(boolean visible) {
labelsVisible = visible;
for (View view : entryViews) {
view.findViewById(R.id.text).setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
#Override
public int getCount() {
return entries.size();
}
#Override
public VideoEntry getItem(int position) {
return entries.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
VideoEntry entry = entries.get(position);
// There are three cases here
if (view == null) {
// 1) The view has not yet been created - we need to initialize the YouTubeThumbnailView.
view = inflater.inflate(R.layout.video_list_item, parent, false);
YouTubeThumbnailView thumbnail = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail);
thumbnail.setTag(entry.videoId);
thumbnail.initialize("AIzaSyB8BPeIbu5T1-flG4tpEdrHDPI3Rk2VTDY", thumbnailListener);
} else {
YouTubeThumbnailView thumbnail = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail);
YouTubeThumbnailLoader loader = thumbnailViewToLoaderMap.get(thumbnail);
if (loader == null) {
// 2) The view is already created, and is currently being initialized. We store the
// current videoId in the tag.
thumbnail.setTag(entry.videoId);
} else {
// 3) The view is already created and already initialized. Simply set the right videoId
// on the loader.
thumbnail.setImageResource(R.drawable.no_thumbnail);
loader.setVideo(entry.videoId);
}
}
TextView label = ((TextView) view.findViewById(R.id.text));
label.setText(entry.text);
label.setVisibility(labelsVisible ? View.VISIBLE : View.GONE);
return view;
}
private final class ThumbnailListener implements
YouTubeThumbnailView.OnInitializedListener,
YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onInitializationSuccess(
YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
loader.setOnThumbnailLoadedListener(this);
thumbnailViewToLoaderMap.put(view, loader);
view.setImageResource(R.drawable.no_thumbnail);
String videoId = (String) view.getTag();
loader.setVideo(videoId);
}
#Override
public void onInitializationFailure(
YouTubeThumbnailView view, YouTubeInitializationResult loader) {
view.setImageResource(R.drawable.no_thumbnail);
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView view, String videoId) {
}
#Override
public void onThumbnailError(YouTubeThumbnailView view, YouTubeThumbnailLoader.ErrorReason errorReason) {
view.setImageResource(R.drawable.no_thumbnail);
}
}
}
public static final class VideoFragment extends YouTubePlayerFragment
implements YouTubePlayer.OnInitializedListener {
private YouTubePlayer player;
private String videoId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize("AIzaSyB8BPeIbu5T1-flG4tpEdrHDPI3Rk2VTDY", this);
}
#Override
public void onDestroy() {
if (player != null) {
player.release();
}
super.onDestroy();
}
public void setVideoId(String videoId) {
if (videoId != null && !videoId.equals(this.videoId)) {
this.videoId = videoId;
if (player != null) {
player.cueVideo(videoId);
}
}
}
public void pause() {
if (player != null) {
player.pause();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean restored) {
this.player = player;
player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
player.setOnFullscreenListener(onFullscreenListener);
if (!restored && videoId != null) {
player.cueVideo(videoId);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
this.player = null;
}
}
private static final class VideoEntry {
private final String text;
private final String videoId;
public VideoEntry(String text, String videoId) {
this.text = text;
this.videoId = videoId;
}
}
private int dpToPx(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}
private static void setLayoutSize(View view, int width, int height) {
ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
private static void setLayoutSizeAndGravity(View view, int width, int height, int gravity) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
params.gravity = gravity;
view.setLayoutParams(params);
}
}
This is my fragment
The layout file is
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/list_fragment"
class="com.mycristoparish.Fragments.VideoGallery$VideoListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
<LinearLayout
android:id="#+id/video_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical">
<ImageButton
android:id="#+id/close_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#android:drawable/btn_dialog" />
<fragment
android:id="#+id/video_fragment_container"
class="com.mycristoparish.Fragments.VideoGallery$VideoFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</merge>
When I try to play the video in full-screen mode I get the following error
java.lang.IllegalArgumentException: Binary XML file line #42: Duplicate id 0x7f0d0117, tag null, or parent id 0x7f0d0115 with another fragment for com.mycristoparish.Fragments.VideoGallery$VideoFragment
Please guide me how can I move further.
Thanks in advance.
The problem is that you are inflating a layout with a fragment inside a fragment.You cannot do it and so you get the error.However you can dynamically add them.
More details
Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically.
I am developing a welcome screen which will show four slides. I have created the adapter and set it in the activity. Every thing is working fine but the problem is the screen only showing first and third slide. But if I scroll manually I can see all the screens. I am not able to figure out why this is happening.
Here is my activity class:
public class ProgramLandingActivity extends AppCompatActivity implements View.OnClickListener {
private String TAG = ProgramLandingActivity.class.getSimpleName();
ActivityProgramLandingBinding binding;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private int[] layouts = {
R.drawable.slider3,
R.drawable.slider1,
R.drawable.slider2,
R.drawable.slider4};
private int[] icons = {
R.drawable.note,
R.drawable.mic,
R.drawable.up_arrow,
R.drawable.weight};
private String[] text = {
"Personalized Running Programs \n and flexible calender",
"Audio tips in Hindi and English \n From your mentors,\n Gul Panag and Milind Soman",
"Track your running, see achievements and share daily progress","includes weight loss and running performance nutrition plans"};
private ArrayList<Integer> layoutArray = new ArrayList<Integer>();
private ArrayList<Integer> layouticons = new ArrayList<Integer>();
private ArrayList<String> layouttext = new ArrayList<String>();
private static int currentPage = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.activity_program_landing);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
intializeViews();
setAdapter();
}
private void setAdapter() {
for (int i = 0; i < layouts.length; i++) {
layoutArray.add(layouts[i]);
layouticons.add(icons[i]);
layouttext.add(text[i]);
myViewPagerAdapter = new MyViewPagerAdapter(this, layoutArray,layouticons,layouttext);
viewPager.setAdapter(myViewPagerAdapter);
CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
Log.d("laypou_length", String.valueOf(layouts.length));
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == layouts.length) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 2500, 2500);
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
private void intializeViews() {
viewPager = (ViewPager) findViewById(R.id.view_pager);
}
My adapter class:
class MyViewPagerAdapter extends PagerAdapter {
private ArrayList<Integer> layouts;
private ArrayList<Integer> icons;
private ArrayList<String> text;
private LayoutInflater inflater;
private Context context;
public MyViewPagerAdapter(Context context,ArrayList<Integer> layouts, ArrayList<Integer> icons,ArrayList<String> text ) {
this.context = context;
this.layouts=layouts;
this.icons = icons;
this.text=text;
inflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View myImageLayout = inflater.inflate(R.layout.slider,container,false);
ImageView myImage = (ImageView) myImageLayout.findViewById(R.id.image1);
ImageView icon = (ImageView)myImageLayout.findViewById(R.id.icon);
TextViewWithFont slider_text = (TextViewWithFont)myImageLayout.findViewById(R.id.text_program_landing_body);
myImage.setImageResource(layouts.get(position));
icon.setImageResource(icons.get(position));
slider_text.setText(text.get(position));
container.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public int getCount() {
return layouts.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
Can someone tell me what I am doing wrong?
try this
you can user time for auto scroll like this
Timer timer;
timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(), 0, 3000); // delay*/
private class RemindTask extends TimerTask {
int current = viewPager.getCurrentItem();
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (current < layouts.length) {
viewPager.setCurrentItem(current);
current += 1;
} else {
timer.cancel();
}
}
});
}
}
Looks like the problem is in the 'viewpager.setCurrentPage' put prints for the 'currentPage' there and see if it is getting called twice.
Let me know the observation in the comments.
Cheers :)
I try to use AsyncTaskLoader in Fragment that is a child of ViewPager. Below a code of my DayFragment:
public class DayFragment extends Fragment
implements LoaderManager.LoaderCallbacks<DayAdapter.DayItem[]> {
private static final int CONTENT_LOADER = 0;
private DayAdapter mAdapter = null;
private int mWeekNumber = 1;
private int mDayCode = 1;
private Table.Timetable mTimetable;
private RecyclerView mRVContent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final MainActivity mainActivity = (MainActivity) getActivity();
View v = inflater.inflate(R.layout.content, container, false);
mRVContent = (RecyclerView) v.findViewById(R.id.rvContent);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mainActivity);
mRVContent.setLayoutManager(layoutManager);
mAdapter = new DayAdapter(getActivity());
mRVContent.setAdapter(mAdapter);
//Initialize the cursor loader
getLoaderManager().initLoader(CONTENT_LOADER, null, this).forceLoad();
return v;
}
#Override
public Loader<DayAdapter.DayItem[]> onCreateLoader(final int id, Bundle args) {
if(CONTENT_LOADER == id) {
return new ContentLoader(getContext(), mWeekNumber, mDayCode, mTimetable);
}
return null;
}
#Override
public void onLoadFinished(Loader loader, DayAdapter.DayItem[] items) {
if(CONTENT_LOADER == loader.getId()) {
mAdapter.setIs24HourFormat(SettingsManager.is24HourFormat(getContext()));
mAdapter.clear();
for (DayAdapter.DayItem item : items) {
mAdapter.add(item);
}
mAdapter.notifyDataSetChanged();
if (items.length == 0) {
mRVContent.setBackgroundResource(R.drawable.bg_lesson_empty);
} else {
mRVContent.setBackgroundColor(0xFFFFFFFF);
}
}
}
#Override
public void onLoaderReset(Loader loader) {
}
private static final class ContentLoader extends AsyncTaskLoader<DayAdapter.DayItem[]> {
private final int mWeekNumber;
private final int mDayCode;
private final Table.Timetable mTimetable;
public ContentLoader(Context context, final int weekNumber, final int dayCode,
Table.Timetable timetable) {
super(context);
mWeekNumber = weekNumber;
mDayCode = dayCode;
mTimetable = timetable;
}
#Override
public DayAdapter.DayItem[] loadInBackground() {
DatabaseHandler db = new DatabaseHandler(getContext());
db.openReadable();
List<Table.Lesson> lessons = db.findLessons(mDayCode, mWeekNumber, mTimetable.getId());
DayAdapter.DayItem[] items = new DayAdapter.DayItem[lessons.size()];
for (int i = 0; i < items.length; ++i) {
Table.Lesson lesson = lessons.get(i);
Table.Subject subject = db.getSubject(lesson.getSubjectId());
Table.Teacher teacher = db.getTeacher(lesson.getTeacherId());
if (teacher == null) {
teacher = new Table.Teacher(""); //Empty name
}
items[i] = new DayAdapter.DayItem()
.setId(lesson.getId())
.setTitle(subject.getTitle())
.setSubtitle(teacher.getName()));
}
db.close();
return items;
}
}
}
PageAdapater
public class PageAdapter extends FragmentStatePagerAdapter {
public static final int PAGE_COUNT = 7;
private int mWeekNumber;
private final int[] mDayCodes;
private final String[] mDays;
private final DayFragment[] mFragments = new DayFragment[7];
private Table.Timetable mTimetable;
private boolean mIsRebuildMode = false;
public PageAdapter(Context context, FragmentManager fm,
Table.Timetable timetable, final int weekNumber) {
super(fm);
//Initialize class members
}
#Override
public Fragment getItem(int position) {
DayFragment dayFragment;
if (mFragments[position] == null) {
dayFragment = new DayFragment();
Bundle args = new Bundle();
args.putSerializable(Keys.TIMETABLE, mTimetable);
dayFragment.setArguments(args);
dayFragment.setWeekNumber(mWeekNumber);
dayFragment.setDayCode(mDayCodes[position]);
mFragments[position]= dayFragment;
} else {
dayFragment = mFragments[position];
}
return dayFragment;
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
//do nothing here! no call to super.restoreState(arg0, arg1);
}
public void setWeekNumber(final int weekNumber) {
mWeekNumber = weekNumber;
Arrays.fill(mFragments, null);
}
public void setIsRebuildMode(final boolean isRebuildMode) {
mIsRebuildMode = isRebuildMode;
}
#Override
public CharSequence getPageTitle(final int position) {
return mDays[position];
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public int getItemPosition(Object object) {
if(mIsRebuildMode) {
return POSITION_NONE;
}
return super.getItemPosition(object);
}
}
But it doesn't call onLoadFinished method. I checked Log output... LoaderManager calls onCreateLoader but it never calls onLoadFinished except first run (when app started and ViewPager shows a first page (Fragment)). It's all! After if I switch a page to a next and a next and return to a first page LoaderManager doesn't call onLoadFinished for the first page too. But it creates loader calling onCreateLoader and resets loader calling onLoaderReset. Is it a joke from Google?
See fragment lifecycle. ViewPager don't re create fragment, just swipe them
-- Start ViewPager
: create
: createView
: start
: resume
not changed if you swipe fragments
--- sleep smartphone
: pause
: stop
--- wakeup smartphone
: start
: resume
: pause
--- Close ViewPager
: stop
: detach
I am working on a RecyclerView which must be Draggable & swipeable. Everything works perfect.
The Data is getting Fetched in one class called ExerciseDataProvider & the RV code is another Fragment RecyclerListViewFragment.
The problem is that i can't notify Data changed from the FetchExercise on postExecute method. So the Data's are not getting populated in the RV.
Please Guide me in a Right Direction.
ACTIVITY
public class DraggableSwipeableExampleActivity extends AppCompatActivity {
private static final String FRAGMENT_TAG_DATA_PROVIDER = "data provider";
private static final String FRAGMENT_LIST_VIEW = "list view";
private static final String FRAGMENT_TAG_ITEM_PINNED_DIALOG = "item pinned dialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(new ExampleDataProviderFragment(), FRAGMENT_TAG_DATA_PROVIDER)
.commit();
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new RecyclerListViewFragment(), FRAGMENT_LIST_VIEW)
.commit();
}
}
public AbstractDataProvider getDataProvider() {
final Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DATA_PROVIDER);
return ((ExampleDataProviderFragment) fragment).getDataProvider();
}
DATA PROVIDER
public class ExerciseDataProvider extends AbstractDataProvider {
private List<ConcreteData> mData;
private ConcreteData mLastRemovedData;
private int mLastRemovedPosition = -1;
public ExerciseDataProvider() {
new FetchExercise().execute();
mData = new LinkedList<>();
}
class FetchExercise extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
final int viewType = 0;
final int swipeReaction = RecyclerViewSwipeManager.REACTION_CAN_SWIPE_UP | RecyclerViewSwipeManager.REACTION_CAN_SWIPE_DOWN;
String url = "https://gist.githubusercontent.com/fake/cb9aa5494e7ee36ac3ca/raw/a4abfd19368063/exercise.JSON";
Log.d("Path", url);
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
final long id = i;
JSONObject jsonObject = jsonArray.getJSONObject(i);
String exercise_name = jsonObject.getString("name");
int exercise_duration = jsonObject.getInt("duration");
mData.add(new ConcreteData(id, viewType, exercise_name, exercise_duration, swipeReaction));
Log.d("exercise_name", exercise_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Data getItem(int index) {
if (index < 0 || index >= getCount()) {
throw new IndexOutOfBoundsException("index = " + index);
}
return mData.get(index);
}
#Override
public int undoLastRemoval() {
if (mLastRemovedData != null) {
int insertedPosition;
if (mLastRemovedPosition >= 0 && mLastRemovedPosition < mData.size()) {
insertedPosition = mLastRemovedPosition;
} else {
insertedPosition = mData.size();
}
mData.add(insertedPosition, mLastRemovedData);
mLastRemovedData = null;
mLastRemovedPosition = -1;
return insertedPosition;
} else {
return -1;
}
}
#Override
public void moveItem(int fromPosition, int toPosition) {
if (fromPosition == toPosition) {
return;
}
final ConcreteData item = mData.remove(fromPosition);
mData.add(toPosition, item);
mLastRemovedPosition = -1;
}
#Override
public void removeItem(int position) {
//noinspection UnnecessaryLocalVariable
final ConcreteData removedItem = mData.remove(position);
mLastRemovedData = removedItem;
mLastRemovedPosition = position;
}
public static final class ConcreteData extends Data {
private final long mId;
private final String mText;
private final int mViewType;
private final int mDuration;
private boolean mPinned;
ConcreteData(long id, int viewType, String text, int duration, int swipeReaction) {
mId = id;
mViewType = viewType;
mText = text;
mDuration = duration;
}
#Override
public int getViewType() {
return mViewType;
}
#Override
public int getDuration() {
return mDuration;
}
#Override
public long getId() {
return mId;
}
#Override
public String toString() {
return mText;
}
#Override
public String getText() {
return mText;
}
#Override
public boolean isPinned() {
return mPinned;
}
#Override
public void setPinned(boolean pinned) {
mPinned = pinned;
}
}
}
RecyclerListViewFragment
public class RecyclerListViewFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.Adapter mAdapter;
private RecyclerView.Adapter mWrappedAdapter;
private RecyclerViewDragDropManager mRecyclerViewDragDropManager;
private RecyclerViewSwipeManager mRecyclerViewSwipeManager;
private RecyclerViewTouchActionGuardManager mRecyclerViewTouchActionGuardManager;
public RecyclerListViewFragment() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recycler_list_view, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//noinspection ConstantConditions
mRecyclerView = (RecyclerView) getView().findViewById(R.id.recycler_view);
mLayoutManager = new LinearLayoutManager(getContext());
// touch guard manager (this class is required to suppress scrolling while swipe-dismiss animation is running)
mRecyclerViewTouchActionGuardManager = new RecyclerViewTouchActionGuardManager();
mRecyclerViewTouchActionGuardManager.setInterceptVerticalScrollingWhileAnimationRunning(true);
mRecyclerViewTouchActionGuardManager.setEnabled(true);
// drag & drop manager
mRecyclerViewDragDropManager = new RecyclerViewDragDropManager();
mRecyclerViewDragDropManager.setDraggingItemShadowDrawable(
(NinePatchDrawable) ContextCompat.getDrawable(getContext(), R.drawable.material_shadow_z3));
// swipe manager
mRecyclerViewSwipeManager = new RecyclerViewSwipeManager();
//adapter
final MyDraggableSwipeableItemAdapter myItemAdapter = new MyDraggableSwipeableItemAdapter(getDataProvider());
myItemAdapter.setEventListener(new MyDraggableSwipeableItemAdapter.EventListener() {
#Override
public void onItemRemoved(int position) {
((DraggableSwipeableExampleActivity) getActivity()).onItemRemoved(position);
}
#Override
public void onItemViewClicked(View v, boolean pinned) {
onItemViewClick(v, pinned);
}
});
mAdapter = myItemAdapter;
mWrappedAdapter = mRecyclerViewDragDropManager.createWrappedAdapter(myItemAdapter); // wrap for dragging
mWrappedAdapter = mRecyclerViewSwipeManager.createWrappedAdapter(mWrappedAdapter); // wrap for swiping
final GeneralItemAnimator animator = new SwipeDismissItemAnimator();
animator.setSupportsChangeAnimations(false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mWrappedAdapter); // requires *wrapped* adapter
mRecyclerView.setItemAnimator(animator);
// additional decorations
//noinspection StatementWithEmptyBody
if (supportsViewElevation()) {
// Lollipop or later has native drop shadow feature. ItemShadowDecorator is not required.
} else {
mRecyclerView.addItemDecoration(new ItemShadowDecorator((NinePatchDrawable) ContextCompat.getDrawable(getContext(), R.drawable.material_shadow_z1)));
}
mRecyclerView.addItemDecoration(new SimpleListDividerDecorator(ContextCompat.getDrawable(getContext(), R.drawable.list_divider_h), true));
mRecyclerViewTouchActionGuardManager.attachRecyclerView(mRecyclerView);
mRecyclerViewSwipeManager.attachRecyclerView(mRecyclerView);
mRecyclerViewDragDropManager.attachRecyclerView(mRecyclerView);
}
#Override
public void onPause() {
mRecyclerViewDragDropManager.cancelDrag();
super.onPause();
}
#Override
public void onDestroyView() {
if (mRecyclerViewDragDropManager != null) {
mRecyclerViewDragDropManager.release();
mRecyclerViewDragDropManager = null;
}
if (mRecyclerViewSwipeManager != null) {
mRecyclerViewSwipeManager.release();
mRecyclerViewSwipeManager = null;
}
if (mRecyclerViewTouchActionGuardManager != null) {
mRecyclerViewTouchActionGuardManager.release();
mRecyclerViewTouchActionGuardManager = null;
}
if (mRecyclerView != null) {
mRecyclerView.setItemAnimator(null);
mRecyclerView.setAdapter(null);
mRecyclerView = null;
}
if (mWrappedAdapter != null) {
WrapperAdapterUtils.releaseAll(mWrappedAdapter);
mWrappedAdapter = null;
}
mAdapter = null;
mLayoutManager = null;
super.onDestroyView();
}
private void onItemViewClick(View v, boolean pinned) {
int position = mRecyclerView.getChildAdapterPosition(v);
if (position != RecyclerView.NO_POSITION) {
((DraggableSwipeableExampleActivity) getActivity()).onItemClicked(position);
}
}
public AbstractDataProvider getDataProvider() {
return ((DraggableSwipeableExampleActivity) getActivity()).getDataProvider();
}
public void notifyItemChanged(int position) {
mAdapter.notifyItemChanged(position);
}
public void notifyItemInserted(int position) {
mAdapter.notifyItemInserted(position);
mRecyclerView.scrollToPosition(position);
}
}
To update recyclerView from onPostExecute in a data provider class, your onPostExecute should have access to context where your recyclerView is defined.
Since your FetchExercise async task is defined inside ExerciseDataProvider class, try passing activity context to ExerciseDataProvider's constructor and then pass it on to FetchExercise async task as described here: getting context in AsyncTask
public class MyCustomTask extends AsyncTask<Void, Void, Long> {
private Context mContext;
public MyCustomTask (Context context){
mContext = context;
}
protected void onPostExecute(Long result) {
//use mContext to update recycler view
}
}
}
Use the context to update the recyclerView.
UPDATE
Step 1
Define an interface that will notify your activity of data set change inside a class that initialises your data provider class and pass activity context to constructor of data provider class.
public class ExampleDataProviderFragment extends Fragment {
private AbstractDataProvider mDataProvider;
//Define an interface that will notify your activity of data set change
public interface EventListener {
void onNotifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
//Pass activity context to ExerciseDataProvider
mDataProvider = new ExerciseDataProvider(getActivity());
}
public AbstractDataProvider getDataProvider() {
return mDataProvider;
}
}
Step 2
Add context parameter to ExerciseDataProvider's constructor and use it to notify activity that implements your interface to notify dataset change.
public class ExerciseDataProvider extends AbstractDataProvider {
private List<ConcreteData> mData;
private ConcreteData mLastRemovedData;
private int mLastRemovedPosition = -1;
//Add context parameter to constructor
public ExerciseDataProvider(Context context) {
//Pass context to async task
new FetchExercise(context).execute();
mData = new LinkedList<>();
}
class FetchExercise extends AsyncTask<Void,Void,Integer> {
Context mContext;
public FetchExercise(Context context) {
mContext = context;
}
#Override
protected Integer doInBackground(Void... params) {
...
return 1;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//Typecast context to interface defined above
//and notify dataset changes by calling its method
ExampleDataProviderFragment.EventListener eventListener = (ExampleDataProviderFragment.EventListener)mContext;
eventListener.onNotifyDataSetChanged();
}
}
}
Step 3
Implement above defined interface in your activity class and notify recyclerview adapter inside it
public class DraggableSwipeableExampleActivity extends AppCompatActivity
implements ExampleDataProviderFragment.EventListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
//implement interface method and notify recyclerview of changes
#Override
public void onNotifyDataSetChanged() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_LIST_VIEW);
// you might need to change visibility of `mWrappedAdapter` in the fragment that defines it or create a getter for it so that you can access it here
((RecyclerListViewFragment) fragment).mWrappedAdapter.notifyDataSetChanged();
}
...
}
I think #random is correct you should be notifying your Recycle view on post execute.
#Override
protected void onPostExecute(Void aVoid) {
mRecyclerViewAdapter.notifyDataSetChanged();
super.onPostExecute(aVoid);
}
or if you have done something in your async task to add/delete something in the data set you would do:
#Override
protected void onPostExecute(Void aVoid) {
mRecyclerViewAdapter.notifyItemRemoved(itemposition); // or item added
mRecyclerViewAdapter.notifyDataSetChanged();
super.onPostExecute(aVoid);
}
Hope it helps !
i am chinese coder.i am not good at english,so just try hard to describe the question. thank you very much for your answer.
when i first into activity with RecyclerView and scroll,it is not smooth especially showing next item next ,but when i have scrolled the Recyclerview,it is work,and smooth . some coder say we can't do much work on onCreateViewHolder() and onBindViewHolder() , but i can not get it.
here is my code:
fragment
public class HomeFragment extends RefreshableFragment implements IHomeView {
#Bind(R.id.refresh_view)
PullToRefreshRecyclerView refresh_view;
private RecyclerView refreshableView;
private HomePresenter homePresenter;
#Override
public View initSuccessView() {
View view = View.inflate(getContext(), R.layout.fragment_refreshable_success_recyclerview, null);
ButterKnife.bind(this, view);
initRefreshLayout();
initRecyclerView();
return view;
}
/**
* 初始化可刷新控件
*/
private void initRefreshLayout() {
refresh_view.setMode(PullToRefreshBase.Mode.BOTH);
refresh_view.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<RecyclerView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
homePresenter.refresh();
}
#Override
public void onPullUpToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
homePresenter.loadMore();
}
});
}
/**
* 初始化RecyclerView控件
*/
private void initRecyclerView() {
refreshableView = refresh_view.getRefreshableView();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
SpaceItemDecoration decor = new SpaceItemDecoration(2);
refreshableView.addItemDecoration(decor);
refreshableView.setLayoutManager(layoutManager);
refreshableView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int childCount = recyclerView.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = recyclerView.getChildAt(i);
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(view);
switch (holder.getItemViewType()){
case HomeAdapter.TYPE_TOPIC:
HomeTopicViewHolder topicViewHolder = (HomeTopicViewHolder) holder;
topicViewHolder.setParentHeight(recyclerView.getHeight());
topicViewHolder.setOffset();
}
}
}
});
}
#Override
protected void requestNetwork() {
homePresenter = new HomePresenter(getContext(),this,null);
homePresenter.init();
}
#Override
public RecyclerView getRecyclerView() {
return refreshableView;
}
#Override
public RefreshView getRefreshView() {
return getParentRefreshView();
}
#Override
public void onRefreshFinish() {
if(refresh_view.isRefreshing()){
refresh_view.onRefreshComplete();
}
}
#Override
public void onLordMoreFinish() {
}
}
presenter
public class HomePresenter extends BasePresenter<IHomeView> implements IHomePresenter, StringLoaderCallback {
private Gson gson;
private HomeAdapter homeAdapter;
private final Pagination pagination;
public HomePresenter(Context context,IHomeView homeView,Bundle bundle) {
super(context,homeView,bundle);
gson = new Gson();
homeAdapter = new HomeAdapter();
getPresenterView().getRecyclerView().setAdapter(homeAdapter);
pagination = new Pagination();
pagination.setLimit(10);
pagination.setOffset(0);
}
#Override
public void init() {
String bannerUrl = ServerAPI.Home.buildHomeBannerUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(bannerUrl, null, bannerUrl, this);
String topicUrl = ServerAPI.Home.buildHomeTopicUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(topicUrl, null, topicUrl, this);
String routeUrl = ServerAPI.Home.buildHomeRouteUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(routeUrl, pagination.getMap(), REFRESH, this);
}
#Override
public void loadMore() {
String routeUrl = ServerAPI.Home.buildHomeRouteUrl();
pagination.setOffset(pagination.getTotal());
pagination.setLimit(10);
NetworkStringLoader.getInstance(context).sendGetStringRequest(routeUrl, pagination.getMap(), LOADMORE, this);
}
#Override
public void refresh() {
pagination.setOffset(0);
pagination.setLimit(10);
pagination.clearTotal();
init();
}
#Override
public void onLoadFinished(String url,Map<String,String> params, String data,Object tag) {
if(url.equals(ServerAPI.Home.buildHomeBannerUrl())){
Log.i(url,data);
HomeBanner.HomeBannerLists homeBannerLists = gson.fromJson(data,HomeBanner.HomeBannerLists.class);
homeAdapter.setBanners(homeBannerLists.list);
}
if(url.equals(ServerAPI.Home.buildHomeTopicUrl())){
Log.i(url,data);
HomeTopic.HomeTopicLists homeTopicLists = gson.fromJson(data,HomeTopic.HomeTopicLists.class);
homeAdapter.setTopics(homeTopicLists.list);
}
if(url.equals(ServerAPI.Home.buildHomeRouteUrl())){
Log.i(url,data);
int mode = (int) tag;
HomeRoute.HomeRouteLists homeRouteLists = gson.fromJson(data, HomeRoute.HomeRouteLists.class);
if (mode == REFRESH){
homeAdapter.setRoutes(homeRouteLists.list);
} else if(mode == LOADMORE){
homeAdapter.appendRoutes(homeRouteLists.list);
}
pagination.appendTotal(homeRouteLists.list.size());
}
getPresenterView().getRefreshView().setCurrentState(RefreshView.STATE_SUCCESS);
getPresenterView().onRefreshFinish();
}
#Override
public void onLoadError(VolleyError error) {
Log.i("error",error.getMessage());
}
}
adapter
public class HomeAdapter extends RecyclerView.Adapter {
public static final int TYPE_BANNER = 0;
public static final int TYPE_TOPIC = 1;
public static final int TYPE_ROUTE = 2;
private List<HomeBanner> banners = new ArrayList<>();
private List<HomeTopic> topics = new ArrayList<>();
private List<HomeRoute> routes = new ArrayList<>();
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case TYPE_BANNER:
View bannerView = HomeBannerViewHolder.getView(parent.getContext());
return new HomeBannerViewHolder(bannerView);
case TYPE_TOPIC:
View topicView = View.inflate(parent.getContext(), R.layout.item_home_topic,null);
// View topicView = HomeTopicViewHolder.getView(parent.getContext());
return new HomeTopicViewHolder(topicView);
case TYPE_ROUTE:
View routeView = View.inflate(parent.getContext(), R.layout.item_home_route,null);
// View routeView = HomeRouteViewHolder.getView(parent.getContext());
return new HomeRouteViewHolder(routeView);
default:
// View defaultView = new View(parent.getContext());
View view = EmptyViewHolder.getView(parent.getContext());
return new EmptyViewHolder(view);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(position == 0){
onBindBannerViewHolder(holder);
}else if(position>0 && position<topics.size()+1){
onBindTopicViewHolder(holder,position-1);
}else {
onBindRouteViewHolder(holder,position-topics.size()-1);
}
}
private void onBindRouteViewHolder(RecyclerView.ViewHolder holder, int position) {
HomeRouteViewHolder routeViewHolder = (HomeRouteViewHolder) holder;
routeViewHolder.setData(routes.get(position));
}
private void onBindTopicViewHolder(RecyclerView.ViewHolder holder,int position) {
HomeTopicViewHolder topicViewHolder = (HomeTopicViewHolder) holder;
topicViewHolder.setData(topics.get(position));
}
private void onBindBannerViewHolder(RecyclerView.ViewHolder holder) {
HomeBannerViewHolder bannerViewHolder = (HomeBannerViewHolder) holder;
bannerViewHolder.setData(banners);
}
#Override
public int getItemCount() {
return 1 + topics.size()+routes.size();
}
#Override
public int getItemViewType(int position) {
if(position == 0){
return TYPE_BANNER;
}else if(position<topics.size()+1){
return TYPE_TOPIC;
}else {
return TYPE_ROUTE;
}
}
public void setBanners(List<HomeBanner> list){
banners.clear();
banners.addAll(list);
notifyDataSetChanged();
}
public void setTopics(List<HomeTopic> list) {
topics.clear();
topics.addAll(list);
notifyDataSetChanged();
}
public void setRoutes(List<HomeRoute> list) {
routes.clear();
routes.addAll(list);
notifyDataSetChanged();
}
public void appendRoutes(List<HomeRoute> list) {
routes.addAll(routes.size(),list);
notifyItemRangeInserted(getItemCount(),list.size());
}
}
holder
public class HomeTopicViewHolder extends BaseViewHolder<HomeTopic> {
private static SimpleDraweeView content_iv ;
private static TextView home_topic_title ;
private static TextView home_topic_discription ;
private int height;
public static View getView(Context context) {
View topicView = View.inflate(context, R.layout.item_home_topic,null);
return topicView;
}
public HomeTopicViewHolder(View itemView) {
super(itemView);
content_iv = (SimpleDraweeView) itemView.findViewById(R.id.home_topic_iv);
if(content_iv!=null){
content_iv = (SimpleDraweeView) itemView.findViewById(R.id.home_topic_iv);
}
if(home_topic_title!=null){
home_topic_title = (TextView) itemView.findViewById(R.id.home_topic_title);
}
if(home_topic_discription!=null){
home_topic_discription = (TextView) itemView.findViewById(R.id.home_topic_discription);
}
if(height==0){
SharedPreferences sp = SharedPreferenceHelper.getInstance().getSharedPreference(itemView.getContext(), SharedPreferenceHelper.EnumSPName.CONFIG);
int scale = sp.getInt(SharedPreferenceHelper.EnumSPName.windowWidth, 0);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(scale,scale);
content_iv.setLayoutParams(layoutParams);
}
}
#Override
protected void inflateView(HomeTopic data) {
NetworkImageLoader loader = NetworkImageLoader.getInstance();
loader.setUrlToSimpleDraweeView(data.getImage(),content_iv);
home_topic_title.setText(data.getName());
home_topic_discription.setText(String.format(getResources().getString(R.string.guider_route),data.getGuide(), data.getRoute()));
}
public void setOffset() {
int itemViewHeight = itemView.getHeight();
int imageViewHeight = content_iv.getHeight();
int parentOffsetMax = (getParentHeight() + itemViewHeight) / 2;
int offsetMax = imageViewHeight - itemViewHeight;
float y = itemView.getY();
float location = y + itemViewHeight/2;
float v = location - getParentHeight() / 2;
float percent = v/parentOffsetMax;
int margin = (int) ((offsetMax/2)*(percent + 1));
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) content_iv.getLayoutParams();
layoutParams.setMargins(0,-margin,0,0);
content_iv.setLayoutParams(layoutParams);
}
public void setParentHeight(int height) {
this.height = height;
}
public int getParentHeight() {
return height;
}
}