Android launch a fragment within a dialog fragment - android

I have a dialog fragment and I need to launch a fragment within this dialog fragment. This means my fragment should occupy the same window as that of dialog fragment. How do I do this? This is my dialog fragment code -
public class CallDialogFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.call_dialog_fragment, container, false);
return view;
}
}

Just use fragment transaction and add another dialog fragment. and add to back stack.

you can use coordinator layout for dialog-fragment.. when you drag layout to upper side it will be your new fragment. and when you drag to down it will be your dialog fragment.
here is the xml code..
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="#dimen/detail_backdrop_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
local:contentScrim="?attr/colorPrimary"
local:expandedTitleMarginEnd="64dp"
local:expandedTitleMarginBottom="22dp"
local:expandedTitleMarginStart="20dp"
local:expandedTitleTextAppearance="#style/TextAppearance.AppCompat.Title"
local:layout_scrollFlags="scroll|exitUntilCollapsed">
<ProgressBar
android:id="#+id/progressfull"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_marginTop="80dp"
android:layout_height="24dp" />
<ImageView
android:id="#+id/image_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
local:layout_collapseMode="parallax"
/>
<View
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:layout_alignBottom="#+id/image_preview"
android:background="?attr/colorPrimary"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarIcon"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light"
local:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
local:borderWidth="0dp"
android:layout_marginRight="#dimen/fab_margin"
android:layout_marginLeft="#dimen/fab_margin"
android:layout_marginTop="#dimen/fab_margin"
android:layout_marginBottom="25dp"
android:src="#drawable/ic_add" />
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
android:background="#color/colorPrimaryDark"
local:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp">
<android.support.v7.widget.CardView
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
fragment_image_slider.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
here is the java code..
public class SlideshowDialogFragment extends DialogFragment {
private String TAG = SlideshowDialogFragment.class.getSimpleName();
private ArrayList<ItemCategories> images;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private String lblCount, lblTitle, lblDate;
private int selectedPosition = 0;
private CardView cardView;
private Context mContext;
public static SlideshowDialogFragment newInstance() {
SlideshowDialogFragment fragmentFullScreen = new SlideshowDialogFragment();
return fragmentFullScreen;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_image_slider, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
setHasOptionsMenu(true);
ViewCompat.setOnApplyWindowInsetsListener(viewPager,
new OnApplyWindowInsetsListener() {
#Override
public WindowInsetsCompat onApplyWindowInsets(View v,
WindowInsetsCompat insets) {
insets = ViewCompat.onApplyWindowInsets(v, insets);
if (insets.isConsumed()) {
return insets;
}
boolean consumed = false;
for (int i = 0, count = viewPager.getChildCount(); i < count; i++) {
ViewCompat.dispatchApplyWindowInsets(viewPager.getChildAt(i), insets);
if (insets.isConsumed()) {
consumed = true;
}
}
return consumed ? insets.consumeSystemWindowInsets() : insets;
}
});
images = (ArrayList<ItemCategories>) getArguments().getSerializable("images");
selectedPosition = getArguments().getInt("position");
Log.e(TAG, "position: " + selectedPosition);
Log.e(TAG, "images size: " + images.size());
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
setCurrentItem(selectedPosition);
getArguments().remove("position");
getArguments().remove("images");
return v;
}
private void setCurrentItem(int position) {
viewPager.setCurrentItem(position, false);
displayMetaInfo(selectedPosition);
}
// page change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
displayMetaInfo(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void displayMetaInfo(int position) {
lblCount = (position + 1) + " of " + images.size();
ItemCategories image = images.get(position);
lblTitle = "" + image.getCategoryItem();
lblDate = "" + image.getUrlThumb();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.style.MyMaterialThemeFull);
}
#Override
public void onDetach() {
super.onDetach();
}
// adapter
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);
ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);
Toolbar toolbarIcon = (Toolbar) view.findViewById(R.id.toolbarIcon);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbarIcon);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = (AppBarLayout) view.findViewById(R.id.appbar);
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenHeight = displaymetrics.heightPixels;
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appBarLayout.getLayoutParams();
lp.height = screenHeight;
toolbarIcon.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag("slideshow");
if (prev != null) {
DialogFragment dialogFullScreen = (DialogFragment) prev;
dialogFullScreen.dismiss();
}
}
});
ItemCategories image = images.get(position);
Glide.with(getActivity()).load(image.getUrlThumb())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageViewPreview);
collapsingToolbar.setTitle(lblTitle);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
just copy this code and you will know what i am talking about

Related

Disable Scrolling in RecyclerView

In code, RecyclerView is in ViewPager.
I wanted enable scrolling in ViewPager when RecyclerView larger than ViewPager.
Unfold All list in recyclerView, How can scroll only viewPager?
I did nestedScrollingEnabled="false" but not working and not good way.
Here is my code
fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="StoreFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
//...
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:gravity="center"
android:background="#color/colorGray">
//...
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
//...
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textMenuMain"
android:nestedScrollingEnabled="false"/>
</RelativeLayout>
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="Activity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Toolbar...>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="1dp"
app:tabTextColor="#000" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</androidx.viewpager.widget.ViewPager>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>
Fragment.java
public class Fragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
List<String> list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment, container, false);
recyclerView = viewGroup.findViewById(R.id.recyclerViewMenu);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
list = new ArrayList<>();
for (int i = 0; i <= 10; i++){
list.add(i+1 + "List");
}
adapter = new MenuListAdapter(list);
recyclerView.setAdapter(adapter);
return viewGroup;
}
}
class MenuListAdapter extends RecyclerView.Adapter<MenuListAdapter.MyViewHolder> {
List<String> list ;
public MenuListAdapter(List<String> lists){
this.list = lists;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.store_menu_item, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
String text = list.get(position);
holder.textMenuName.setText(text);
holder.textMenuPrice.setText("Price:00");
}
#Override
public int getItemCount() {
return this.list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textMenuName;
TextView textMenuPrice;
Button buttonCartAdd;
public MyViewHolder(View view){
super(view);
textMenuName = (TextView) view.findViewById(R.id.textMenuName);
textMenuPrice = (TextView) view.findViewById(R.id.textMenuPrice);
buttonCartAdd = (Button) view.findViewById(R.id.buttonCartAdd);
}
}
}
Activity.java
public class Activity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
TextView textViewNotice;
TextView textViewTitle;
String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_detail);
tabLayout = findViewById(R.id.tabs);
viewPager = findViewById(R.id.pager);
textViewNotice = findViewById(R.id.textNotice);
textViewTitle = findViewById(R.id.textTitle);
textViewNotice.setSelected(true);
Intent intent = getIntent();
title = intent.getExtras().getString("Title");
textViewTitle.setText(title);
tabLayout.addTab(tabLayout.newTab().setText("정보"));
tabLayout.addTab(tabLayout.newTab().setText("리뷰"));
Activity.MyPagerAdapter adapter = new Activity.MyPagerAdapter(getSupportFragmentManager());
Fragment Fragment = new Fragment();
adapter.addItem(Fragment);
//...
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> items = new ArrayList<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addItem(Fragment item) {
items.add(item);
}
#NonNull
#Override
public Fragment getItem(int position) {
return items.get(position);
}
#Override
public int getCount() {
return items.size();
}
}
}
Try this
LinearLayoutManager layoutManager = new LinearLayoutManager(context) {
#Override
public boolean canScrollVertically() {
return false;
}
};
recyclerView.setLayoutManager(layoutManager);

ViewPager not showing anything - android

I need some advice. ViewPager showing just white page. I have searched much, but I couldn't find solution for my case.
I tried to make simple button, but I got same output. I think it's not image problem.
Here's my code.
public class IntroduceArticleFragment extends Fragment {
View view;
String depart;
String path;
int num;
CustomPagerAdapter customPagerAdapter;
ViewPager viewPager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_introduce_article, container, false);
view.setBackgroundColor(Color.WHITE);
depart = getArguments().getString("depart");
create();
//customPagerAdapter = new CustomPagerAdapter(getActivity());
viewPager = (ViewPager)view.findViewById(R.id.pager);
viewPager.setAdapter(customPagerAdapter);
return view;
}
void create(){
DBHelper dbHelper = new DBHelper(getActivity());
path = dbHelper.getContentsPath(depart);
num = dbHelper.getNum(depart);
customPagerAdapter = new CustomPagerAdapter(getActivity());
customPagerAdapter.mResources = new int[num];
for(int i=0;i<num;i++) {
String uri = "#drawable/" + path + "_" + Integer.toString(i);
int imageResource = getActivity().getResources().getIdentifier(uri, "drawabale", getActivity().getPackageName());
customPagerAdapter.mResources[i] = imageResource;
}
}
}
public class CustomPagerAdapter extends PagerAdapter {
Context mContext;
public int[] mResources;
public CustomPagerAdapter(Context context) {
super();
mContext = context;
}
#Override
public int getCount() {
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.pager_item_0, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.pagerimageView_0);
imageView.setImageResource(mResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
#Override
public void startUpdate(ViewGroup container) {
super.startUpdate(container);
}
#Override
public void finishUpdate(ViewGroup container) {
super.finishUpdate(container);
}
}
and here's xml code for ArticleFragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:visibility="visible">
</android.support.v4.view.ViewPager>
</LinearLayout>
</ScrollView>
</LinearLayout>
and here's xml code for
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:id="#+id/pagerimageView_0" />
</LinearLayout>
Ok... First of all you must set the android:layout_height of the ScrollView's child to wrap_content.
Second, Consider that you can't set android:layout_height of ViewPager to wrap_content. Unless you use a custom ViewPager. For Example you can check this answer
By setting android:fillViewport to true in ScrollView, The height of ScrollView's Child automatically will set to match_parent until its height become taller than screen.
And I don't get it why you set the height of ViewPager to 0dp and expect that it shows something!
Now your layout should be like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_pranet"
android:visibility="visible">
</android.support.v4.view.ViewPager>
</LinearLayout>
</ScrollView>
</LinearLayout>
I've spent half of day solving it and gets that my ViewPager have the same id with another ViewPager in another module in my app, so I've simply gave it another id.
You Have got it all wrong, use this code
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class CustomPagerAdapter extends FragmentStatePagerAdapter {
public int[] mResources;
public NewsAdapter(FragmentManager fm, int[] mResources) {
super(fm);
this.mNumOfTabs = mResources.length();
this.mResources = mResources;
}
#Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(mResources[position]);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
public class ContentFragment extends Fragment {
private Context context;
private int resource_id;
public static ContentFragment newInstance(int resourdid) {
Bundle args = new Bundle();
args.putInt("resource_id", resourdid);
ContentFragment fragment = new ContentFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resource_id = getArguments().getInt("resource_id");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(in.newswallet.R.layout.content_row, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initalize();
}
private void initalize(){
View itemView = getView();
ImageView imageView = (ImageView) itemView.findViewById(R.id.pagerimageView_0);
imageView.setImageResource(resource_id);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
}
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:visibility="visible">
</android.support.v4.view.ViewPager>
try to change the android:layout_height = "0dp" to some value like android:layout_height = "50dp" or
give weight to the layout
android:layout_weight = "1"
Change:
container.removeView((LinearLayout) object);
With:
container.removeView((ConstraintLayout) object);

design layout like this image what is use to design

[ http://i.stack.imgur.com/Re29U.png]
left right swipe center value automatically checked and related table show in layout.
try this
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView[] dots;
private LinearLayout dotsLayout;
// Declare Variables
ViewPager viewPager;
String[] CustomerNameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomerNameList = new String[]{"xxxxx", "sssss", "aaaaaa", "ffffff", "gggggggg", "jjjjj"};
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
addBottomDots(0);
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) findViewById(R.id.first_customer_popup_view_pager);
// Pass results to ViewPagerAdapter Class
CustomPagerAdapter adapter = new CustomPagerAdapter(this, CustomerNameList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
private void addBottomDots(int currentPage) {
dots = new TextView[CustomerNameList.length];
int colorsActive = Color.rgb(102, 41, 125);
int colorsInactive = Color.rgb(217, 217, 217);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(100);
dots[i].setTextColor(colorsInactive);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive);
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
}
CustomPagerAdapter.java
public class CustomPagerAdapter extends PagerAdapter {
private Context context;
private String[] CustomerNameList;
LayoutInflater inflater;
public CustomPagerAdapter(Context context,String[] CustomerNameList) {
this.context = context;
this.CustomerNameList = CustomerNameList;
}
#Override
public int getCount() {
return CustomerNameList.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
TextView AO_investments_list_popup_name;
TextView AO_investments_list_popup_na;
ListView all_listView;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.adapter_single_page, container, false);
// Locate the TextViews in viewpager_item.xml
AO_investments_list_popup_name = (TextView) itemView.findViewById(R.id.display);
AO_investments_list_popup_name.setText(CustomerNameList[position]);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.agthamays.sof_1.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/first_customer_popup_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#color/colorAccent"
android:gravity="center|center_vertical"
android:orientation="horizontal">
</LinearLayout>
</RelativeLayout>
</LinearLayout>
adapter_single_page.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:background="#color/colorPrimaryDark"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:id="#+id/display"
android:layout_width="wrap_content"
android:text="xxxx"
android:textSize="24dp"
android:paddingLeft="100dp"
android:textStyle="bold"
android:textColor="#color/colorAccent"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</LinearLayout>

First element in ViewPager is displayed incorrectly

I'm using RecyclerView to display list of elements and from that list u can go to detailed screen, which is view pager fragment. My problem is that first element I navigate to (from RecyclerView) is displayed incorrectly - it has NestedScrollView, which I cannot fully scroll down. If I swype left or right to next pages, they are fine, it's always one that is loaded as first.
My Adapter class is following;
public class ApodViewAdapter extends FragmentStatePagerAdapter {
private ArrayList<APOD> mDataset;
public ApodViewAdapter(FragmentManager fm, ArrayList<APOD> apodsList) {
super(fm);
setData(apodsList);
}
public void setData(ArrayList<APOD> apodsList){
if(apodsList!=null){
this.mDataset= apodsList;
notifyDataSetChanged();
}
}
#Override
public Fragment getItem(int position) {
return new ApodViewFragment().newInstance(mDataset.get(position), position);
}
#Override
public int getCount() {
return mDataset.size();
}
}
Fragment Activity:
public class ApodViewFragment extends Fragment implements DataInterface, AppBarLayout.OnOffsetChangedListener {
private ImageView mApodImageView;
private TextView mTextView;
private Toolbar mToolbar;
private AppBarLayout mAppBarLayout;
private TextView mTitle;
private FrameLayout mContentFl;
private APOD mApodElement;
private static final String KEY_CONTENT = "ApodViewFragment:Content";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mApodElement = (APOD) savedInstanceState.getSerializable(KEY_CONTENT);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_CONTENT, mApodElement);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_apod_material, container, false);
mApodImageView = (ImageView) rootView.findViewById(R.id.apod_view_apod_iv);
mTextView = (TextView) rootView.findViewById(R.id.apod_view_text_tv);
mTitle = (TextView) rootView.findViewById(R.id.apod_fragment_title_tv);
mContentFl = (FrameLayout) rootView.findViewById(R.id.fragment_apod_fl);
mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
mAppBarLayout = (AppBarLayout) rootView.findViewById(R.id.app_bar_layout);
mAppBarLayout.addOnOffsetChangedListener(this);
ViewTreeObserver vto = mContentFl.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
setHeroImageMaxHeight();
ViewTreeObserver obs = mContentFl.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
obs.removeOnGlobalLayoutListener(this);
} else {
obs.removeGlobalOnLayoutListener(this);
}
}
});
setData();
return rootView;
}
public static ApodViewFragment newInstance(APOD apodElement, int position) {
ApodViewFragment fragment = new ApodViewFragment();
fragment.mApodElement = apodElement;
return fragment;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void saveData(APOD apodElement) {
}
#Override
public void readData() throws IOException {
}
private void setData() {
if(mApodElement.getMedia_type().equals("video")){
Picasso.with(getActivity()).load(R.drawable.videoplaceholder).into(mApodImageView);
}else{
Picasso.with(getActivity()).load(mApodElement.getUrl()).into(mApodImageView);
}
mTextView.setText(mApodElement.getExplanation());
mTitle.setText(mApodElement.getTitle());
}
private void setHeroImageMaxHeight(){
int screenHeight = ImageHelper.getDisplayHeight(getActivity());
mToolbar.getLayoutParams().height = screenHeight - mContentFl.getHeight();
mToolbar.requestLayout();
}
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
float minimalTextSize = getActivity().getResources().getDimensionPixelSize(R.dimen.apod_view_title_scrolling_text_size);
float maximumTextSize = getActivity().getResources().getDimensionPixelSize(R.dimen.apod_view_title_default_text_size);
float absolut_offset = Math.abs(offset);
float text_size_difference = maximumTextSize - minimalTextSize;
float scale = (absolut_offset) / (appBarLayout.getHeight() - absolut_offset);
if (offset < 0) {
float result = maximumTextSize - (scale * text_size_difference);
mTitle.setTextSize(FontHelper.pixelsToSp(getActivity(), result));
} else {
mTitle.setTextSize(FontHelper.pixelsToSp(getActivity(), maximumTextSize));
}
}
}
And XML layout file
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/apod_fragment_ctl"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:expandedTitleMarginStart="16dp"
android:fitsSystemWindows="true">
<ImageView
android:id="#+id/apod_view_apod_iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="wrap_content"
android:fitsSystemWindows="true"
android:layout_height="wrap_content">
<TextView
android:id="#+id/apod_fragment_title_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:textSize="#dimen/apod_view_title_default_text_size"
android:layout_alignParentBottom="true"
app:layout_collapseMode="pin"
/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:background="#android:color/holo_purple"
android:fitsSystemWindows="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<FrameLayout
android:id="#+id/fragment_apod_fl"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:layout_gravity="center_vertical"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:text="TITLE"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:textAppearance="#style/TextAppearance.AppCompat.Headline"/>
<TextView
android:id="#+id/apod_view_text_tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
app:layout_anchor="#id/cardview"
app:layout_anchorGravity="top|right|end"
android:src="#drawable/ic_rocket_em_blank"
android:layout_margin="16dp"
app:backgroundTint="#android:color/holo_purple"
style="#style/FabStyle"/>
</android.support.design.widget.CoordinatorLayout>
I'd say that reason must be somewhere in Adapter or fragment's methods, which create new Fragment, but can't really find it. Any help appreciated, cheers!

CirclePageIndicator on top of ViewPager

In my layout I am trying to get the CirclePageIndicator to sit at the bottom of my image and for my image to be aligned at the top of the screen. Whatever I try it doesn't work. Here is how I want it to look like:
What it ends up looking like is this
Here is my code for this.
<RelativeLayout android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_gravity="top">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="3dp"/>
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/pager"/>
</RelativeLayout>
And because it is a ViewPager I added the ability to scroll through each image. Here is the code for that.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private int[] Images = new int[] { R.drawable.homephoneicon1, R.drawable.homephoneicon2,
R.drawable.homephoneicon3, R.drawable.homephoneicon4, R.drawable.homephoneicon5};
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return SlideshowFragment.newInstance(Images[position]);
}
#Override
public int getCount() {
return NUM_SLIDES;
}
}
Here is the Slideshow code
public class SlideshowFragment extends Fragment {
int imageResourceId;
public static SlideshowFragment newInstance(int i) {
SlideshowFragment fragment = new SlideshowFragment();
fragment.imageResourceId = i;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
image.setImageResource(imageResourceId);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.setGravity(Gravity.TOP);
layout.addView(image, params);
return layout;
}
}
Thanks for any help!
Here is how I did it
Code
public static SlideshowFragment newInstance(int i) {
SlideshowFragment fragment = new SlideshowFragment();
fragment.imageResourceId = i;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
image.setImageResource(imageResourceId);
image.setScaleType(ImageView.ScaleType.FIT_XY);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
RelativeLayout layout = new RelativeLayout(getActivity());
layout.setLayoutParams(new LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
layout.addView(image, params);
return layout;
}
Layout
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.5">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="5dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
late comer but seems a better workaround
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="#dimen/height"/>
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="5dp"
android:layout_alignBottom="#+id/pager"/>
activity_main.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="fill_parent"
android:background="#ffffff"
android:layout_height="300dp">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="300dp"></android.support.v4.view.ViewPager>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:background="#android:color/transparent"
android:gravity="center_horizontal"
android:textSize="50sp" />
</RelativeLayout>
view_pager_item.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/pagerItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textAlignment="center" />
</RelativeLayout>
ViewPagerAdapter.java:-
public class ViewPagerAdapter extends PagerAdapter {
Context con;
String[] data;
public ViewPagerAdapter(Context con, String[] data) {
this.data = data;
this.con = con;
}
#Override
public int getCount() {
return data.length;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.view_pager_item, container, false);
try {
TextView textView = (TextView) view.findViewById(R.id.pagerItem);
textView.setText(data[position]);
((ViewPager) container).addView(view);
} catch (Exception ex) {
ex.printStackTrace();
}
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
MainActivity.java:-
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] data = new String[]{
"page 1",
"page 2",
"page 3",
"page 4"
};
final ViewPagerAdapter adapter = new ViewPagerAdapter(this, data);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setOffscreenPageLimit(2);
viewPager.setAdapter(adapter);
final TextView textView = (TextView) findViewById(R.id.textView);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
textView.setText("");
for (int i = 0; i < adapter.getCount(); i++) {
Spannable word = new SpannableString(" " + ".");
if (i == position) {
word.setSpan(new ForegroundColorSpan(Color.RED), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
textView.append(word);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Simple way import pagerlibrary and use this code into .xml file.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_above="#+id/twoImage"
android:id="#+id/slideLay"
>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/offer_pager"
/>
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/page_indicatorr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#null"
app:fillColor="#000000"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="10dp"
android:padding="5dip"
>
</com.viewpagerindicator.CirclePageIndicator>
</RelativeLayout>

Categories

Resources