I want to change the layout by swyping over the tabs with fragments. Can anybody help me solve my problem?
Here is my fragmentactivity:
public class MainActivity extends FragmentActivity {
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private Drawable oldBackground = null;
private int currentColor = 0xFF666666;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
changeColor(currentColor);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_contact:
QuickContactFragment dialog = new QuickContactFragment();
dialog.show(getSupportFragmentManager(), "QuickContactFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
private void changeColor(int newColor) {
tabs.setIndicatorColor(newColor);
// change ActionBar color just if an ActionBar is available
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Drawable colorDrawable = new ColorDrawable(newColor);
Drawable bottomDrawable = getResources().getDrawable(R.drawable.actionbar_bottom);
LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable, bottomDrawable });
if (oldBackground == null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
ld.setCallback(drawableCallback);
} else {
getActionBar().setBackgroundDrawable(ld);
}
} else {
TransitionDrawable td = new TransitionDrawable(new Drawable[] { oldBackground, ld });
// workaround for broken ActionBarContainer drawable handling on
// pre-API 17 builds
// https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
td.setCallback(drawableCallback);
} else {
getActionBar().setBackgroundDrawable(td);
}
td.startTransition(200);
}
oldBackground = ld;
// http://stackoverflow.com/questions/11002691/actionbar-setbackgrounddrawable-nulling-background-from-thread-handler
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowTitleEnabled(true);
}
currentColor = newColor;
}
public void onColorClicked(View v) {
int color = Color.parseColor(v.getTag().toString());
changeColor(color);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentColor", currentColor);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentColor = savedInstanceState.getInt("currentColor");
changeColor(currentColor);
}
private Drawable.Callback drawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
getActionBar().setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postAtTime(what, when);
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
"Top New Free", "Trending" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
And here is my fragment that writes the numbers of the positions in a text view:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
public class SuperAwesomeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
FrameLayout fl = new FrameLayout(getActivity());
fl.setLayoutParams(params);
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources()
.getDisplayMetrics());
TextView v = new TextView(getActivity());
params.setMargins(margin, margin, margin, margin);
v.setLayoutParams(params);
v.setLayoutParams(params);
v.setGravity(Gravity.CENTER);
v.setBackgroundResource(R.drawable.background_card);
v.setText("CARD " + (position + 1));
fl.addView(v);
return fl;
}
}
the library and the full code of the sample you can found here:
https://github.com/astuetz/PagerSlidingTabStrip
I know its late but might help someone:
Here is the quick fix:
Create other layouts first, let's assume that you create 3: I am also assuming the layout to give a clear idea
layout/lay1.xml - has a textview only
layout/lay2.xml - has an imageview only
layout/lay3.xml - has both textview and imageview
now inside oncreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// if else or switch case, your wish
View view;
if (position == 0) {
// means lay1.xml
view = inflater.inflate(R.layout.lay1, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText("Content not available");
return view;
} else if (position == 1) {
// means lay2.xml
view = inflater.inflate(R.layout.lay2, container, false);
ImageView imagebg = (ImageView) view.findViewById(R.id.image1);
imagebg.setImageResource(R.drawable.ic_launcher);
return view;
} else {
// means lay3.xml
view = inflater.inflate(R.layout.lay3, container, false);
ImageView imagebg = (ImageView) view.findViewById(R.id.image1);
imagebg.setImageResource(R.drawable.ic_launcher);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText("this is working wow, thanks.");
return view;
}
}
Related
I have implemented a ViewPager in my application which consist of two slides. I can go from first slide to second slide and reverse as well. But I have a special case here. If the user goes from First Slide to Second Slide. He should not be able to go back to the First slide. I need to disable going back to the First Slide once he enters the Second Slide.
Here is my code:
public class BotConnectionDialog extends DialogFragment {
private RelativeLayout toolbar;
private ImageView toolbarCloseButton;
private View layoutView;
private ViewPager viewPager;
private BotConnectionDialogAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
int width, height;
DisplayMetrics metrics;
private int[] layouts;
private final String TAG = BotConnectionDialog.class.getSimpleName();
private Button btnSkip, btnNext;
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().popBackStackImmediate();
}
});
}
};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.botconnection_layout, container, false);
Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/corbert.otf");
toolbar = (RelativeLayout) rootView.findViewById(R.id.customAppBarLayout);
toolbar.setBackgroundColor(Color.parseColor("#00000000"));
toolbarCloseButton = (ImageView) rootView.findViewById(R.id.toolbarCloseButton);
toolbarCloseButton.setOnClickListener(myListener);
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) rootView.findViewById(R.id.layoutDots);
btnSkip = (Button) rootView.findViewById(R.id.btn_skip);
btnSkip.setTypeface(typeface);
btnNext = (Button) rootView.findViewById(R.id.btn_next);
btnNext.setTypeface(typeface);
metrics = getResources().getDisplayMetrics();
width = metrics.widthPixels;
height = metrics.heightPixels;
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.slide1,
R.layout.slide2};
// adding bottom dots
addBottomDots(0);
myViewPagerAdapter = new BotConnectionDialogAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
}
}
});
return rootView;
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
/**
* bluetooth connection the bot
*/
Toast.makeText(getActivity(), "Finished", Toast.LENGTH_SHORT).show();
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
/**
* First page
*/
Toast.makeText(getActivity(), "2nd page", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
//dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public void onResume() {
super.onResume();
// getDialog().getWindow().setLayout((7 * width) / 7, (4 * height) / 5);
}
public class BotConnectionDialogAdapter extends PagerAdapter {
/**
* View pager adapter
*/
private LayoutInflater layoutInflater;
public BotConnectionDialogAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
/**
* To disable and enable scrolling on ViewPager, just set shouldScroll to true or false.
*/
public class ScrollableViewPager extends ViewPager {
private boolean shouldScroll = true;
public ScrollableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setShouldScroll(boolean shouldScroll) {
this.shouldScroll = shouldScroll;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return shouldScroll && super.onTouchEvent(ev);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return shouldScroll && super.onInterceptTouchEvent(ev);
}
}
Now use this ScrollableViewPager in place of the default ViewPager and in your onPageSelected() callback
check for the position. If it is the last position, call the setShouldScroll(false) method on your viewPager instance, which will make shouldScroll to false in our ScrollableViewPager class and eventually make the scrolling invalid as we have overridden onTouchEvent() and onInterceptTouchEvent() method, which checks for the value of shouldScroll.
FragmentClass
public class BlankFragment extends Fragment {
//FragmentClass constructor with no parameter
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
**Inflating recyclerView with Dummy data i want to load data from firebase here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
//FInding recyclerViewByid
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
// i have added dummy data into adapter but want toadd data from firebaseDatabase into Myadapter
MyAdapter adapter = new MyAdapter(new String[] {
"test one", // i have hardcoded these data
"test two", // but i want data from firebase to go here
"test three",
"test four",
"test five",
"test six",
"test seven"
});
rv.setAdapter(adapter); //Setting adapter
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView; // returning rootView
}
}
MainActivity
#MainActivity contains 3TabLayouts
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private final String TAG = "SOMETHING";
private ImageView image;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
//TabLayout
TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
PagerAdapter pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if (position == 1)
Log.d(TAG, "onTabSelected: "); //call some method
else if (position == 2)
Log.d(TAG, "onTabSelected: "); //call some method
else
Log.d(TAG, "onTabSelected: "); //call some method
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//SettingViewpagers
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
#Override
public void onResume() {
super.onResume();
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] {
"NOTICE", // tab1 header
"FEED", // tab2 header
"RESULT" // tab3 header
};
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
// 3 tab classes
want to load different data in all 3 tabs
all data should be loaded from firebase
switch (position) {
case 0:
return new BlankFragment(); //FragementClass 1
case 1:
return new BlankFragment(); //FragmentClass 2
case 2:
return new SomeFragment(); //FragmentClass 3
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
// inflate some value should inflate some custom view here
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
#Adapter class
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;
public class MyAdapter extends RecyclerView.Adapter < MyAdapter.MyViewHolder > {
private String[] mDataset;
private final static int FADE_DURATION = 1000;
public MyAdapter() {
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText((CharSequence) mDataset[position]);
setScaleAnimation(holder.mCardView);
// setFadeAnimation(holder.mTextView);
;
}
//adding simple scale animation to CardView
private void setScaleAnimation(View view) {
ScaleAnimation anim = new ScaleAnimation(0.0 f, 1.0 f, 0.0 f, 1.0 f, Animation.RELATIVE_TO_SELF, 0.5 f, Animation.RELATIVE_TO_SELF, 0.5 f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
//Adding Fade animation
private void setFadeAnimation(View view) {
AlphaAnimation anim = new AlphaAnimation(0.0 f, 1.0 f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
I want to add gridview layout inside the tab layout of my current project is there any way I can add it or maybe inflate it with my current code?
This is my current mainactivity.java:
package id.WKKR.ktcafe;
import tabs.SlidingTabLayout;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
#
SuppressWarnings("deprecation")
public class MenuUtama extends ActionBarActivity {
GridView myGridView;
Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_utama);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
NavDrawerFragment drawerFragment = (NavDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
mPager = (ViewPager) findViewById(R.id.MyPager);
mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mTabs = (SlidingTabLayout) findViewById(R.id.MyTabs);
mTabs.setDistributeEvenly(true);
mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabsText);
mTabs.setBackgroundColor(getResources().getColor(R.color.orange));
mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.brown));
mTabs.setViewPager(mPager);
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_utama, menu);
return true;
}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(this, "This Is " + item.getTitle() + " Button", Toast.LENGTH_SHORT).show();
return true;
}
if (id == R.id.bill) {
startActivity(new Intent(this, BillTagihanAnda.class));
}
if (id == R.id.pesanan) {
startActivity(new Intent(this, DaftarPesananAnda.class));
}
if (id == R.id.callwaiter) {
startActivity(new Intent(this, PanggilPelayan.class));
finish();
}
return super.onOptionsItemSelected(item);
}
class MyPagerAdapter extends FragmentPagerAdapter {
int icon[] = {
R.drawable.ic_food, R.drawable.ic_drink, R.drawable.ic_desserts
};
String[] tabsText = getResources().getStringArray(R.array.tabs);
public MyPagerAdapter(FragmentManager fm) {
super(fm);
tabsText = getResources().getStringArray(R.array.tabs);
}
#
Override
public Fragment getItem(int position) {
MyFragment myFragment = MyFragment.getInstance(position);
return myFragment;
}
#
Override
public CharSequence getPageTitle(int position) {
Drawable drawable = getResources().getDrawable(icon[position]);
drawable.setBounds(0, 0, 40, 40);
ImageSpan imageSpan = new ImageSpan(drawable);
SpannableString spannableString = new SpannableString(" ");
spannableString.setSpan(imageSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
#
Override
public int getCount() {
return 3;
}
}
public static class MyFragment extends Fragment {
private TextView textView;
public static MyFragment getInstance(int position) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("position", position);
myFragment.setArguments(args);
return myFragment;
}
#
Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.my_fragment, container, false);
textView = (TextView) layout.findViewById(R.id.position);
Bundle bundle = getArguments();
if (bundle != null) {
textView.setText("The Page Selected is " + bundle.getInt("position"));
}
return layout;
}
}
}
and this is how the tab layout look like, it inflate the textview that showing the current position from array
http://i59.tinypic.com/9jopyc.jpg[/IMG]
thanks for anyone who want to help.
so i already add the gridview, now i was trying to inflate the gridview with image and textview, i'm using an adapter which look like this, but honestly i don't know how to make it works :
public static class MyFragment extends Fragment {
private TextView textView;
private GridView myGridView;
public static MyFragment getInstance(int position) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("position", position);
myFragment.setArguments(args);
return myFragment;
}
#
Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.my_fragment, container, false);
textView = (TextView) layout.findViewById(R.id.position);
myGridView = (GridView) layout.findViewById(R.id.gridView);
Bundle bundle = getArguments();
if (bundle != null) {
textView.setText("The Page Selected is " + bundle.getInt("position"));
}
return layout;
}
}
class Menus {
int imageId = 0;
String menus = "";
String menusPrices = "";
Menus(int imageId, String menus, String menusPrices) {
this.imageId = imageId;
this.menus = menus;
this.menusPrices = menusPrices;
}
}
//the adapter which inflate the gridview content
class MyCafe extends BaseAdapter {
ArrayList < Menus > list;
Context context;
MyCafe(Context context) {
this.context = context;
list = new ArrayList < Menus > ();
Resources res = context.getResources();
String[] tempMenusNames = res.getStringArray(R.array.food);
String[] tempMenusPrices = res.getStringArray(R.array.foodprices);
int[] menusImages = {
R.drawable.makanana, R.drawable.makananb,
R.drawable.makananc, R.drawable.makanand,
R.drawable.makanane, R.drawable.makananf
};
for (int i = 0; i < 6; i++) {
Menus tempMenus = new Menus(menusImages[i], tempMenusNames[i],
tempMenusPrices[i]);
list.add(tempMenus);
}
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int i) {
// TODO Auto-generated method stub
return list.get(i);
}
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
class ViewHolder {
ImageView myMenus;
TextView myMenusText;
TextView MyMenusPrice;
ViewHolder(View v) {
myMenus = (ImageView) v.findViewById(R.id.imageView1);
myMenusText = (TextView) v.findViewById(R.id.textView1);
MyMenusPrice = (TextView) v.findViewById(R.id.textView2);
}
}
public View getView(int i, View view, ViewGroup viewGroup) {
// TODO Auto-generated method stub
View row = view;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.single_item, viewGroup, false);
holder = new ViewHolder(row);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Menus temp = list.get(i);
holder.myMenus.setImageResource(temp.imageId);
holder.myMenusText.setText(temp.menus);
holder.MyMenusPrice.setText(temp.menusPrices);
return row;
}
}
Create grid view inside R.layout.my_fragment and inflate in fragment.
You can also use multiple fragment in your pager adapter.
Good morning guys, its quite long time I'm trying to show a custom text in my DialogFragment, but still I got nothing, I have multiple tabs inside an acitivty that extends FragmentActivity and implements TabListener, here is how I call the dialog:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_contact:
QuickContactFragment dialog = new QuickContactFragment();
dialog.show(getSupportFragmentManager(), "QuickContactFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
and here is my dialog body:
public class QuickContactFragment extends DialogFragment {
View view;
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private ContactPagerAdapter adapter;
public static QuickContactFragment newInstance() {
QuickContactFragment f = new QuickContactFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
if (getDialog() != null) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
}
View root = inflater.inflate(R.layout.fragment_quick_contact, container,
false);
tabs = (PagerSlidingTabStrip) root.findViewById(R.id.tabs);
pager = (ViewPager) root.findViewById(R.id.pager);
adapter = new ContactPagerAdapter();
pager.setAdapter(adapter);
tabs.setViewPager(pager);
return root;
}
#SuppressWarnings("deprecation")
#Override
public void onStart() {
super.onStart();
// change dialog width
if (getDialog() != null) {
int fullWidth = getDialog().getWindow().getAttributes().width;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Display display =
getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
fullWidth = size.x;
} else {
Display display =
getActivity().getWindowManager().getDefaultDisplay();
fullWidth = display.getWidth();
}
final int padding = (int)
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
.getDisplayMetrics());
int w = fullWidth - padding;
int h = getDialog().getWindow().getAttributes().height;
getDialog().getWindow().setLayout(w, h);
}
}
public class ContactPagerAdapter extends PagerAdapter implements IconTabProvider {
private final int[] ICONS = { R.drawable.ic_launcher_gplus,
R.drawable.ic_launcher_gmail,
R.drawable.ic_launcher_gmaps,
R.drawable.ic_launcher_chrome };
public ContactPagerAdapter() {
super();
}
//here is implemention too
//here shows how many tabs should it predict.. i can set N=0 and every
time a notification comes, set N=N+1, and then whenever delete happenes, N=N-1 ;D
#Override
public int getCount() {
return ICONS.length;
}
////this is implemented method by the icontabprovider.. just figure it to set image
on IF
down there,
#Override
public int getPageIconResId(int position) {
return ICONS[position];
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// looks a little bit messy here
TextView v = new TextView(getActivity());
v.setBackgroundResource(R.color.background_window);
if (position == 2){
v.setText("this is page 3 :D");
TextView tv =(TextView)getActivity().findViewById(R.id.quickcontacttext);
tv.setText("have you heared it? just bieber is pragnent !");
}
else{
v.setText("PAGE " + (position + 1));
}
final int padding = (int)
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources()
.getDisplayMetrics());
v.setPadding(padding, padding, padding, padding);
v.setGravity(Gravity.CENTER);
container.addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View) view);
}
#Override
public boolean isViewFromObject(View v, Object o) {
return v == ((View) o);
}
}
}
Where I need to set text , is where page changes, but as more as I try , more I get fraustrated, could you guys throw some help here please? thanks by the way
Inside onCreateView of you DialogFragment you should do:
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("This is an instance of MyDialogFragment");
Check the DialogFragment Reference
I use PagerView in my application. But I have mistake. I load image in each pages. On all pages I see my images. but the page that has a position 0 in pagerAdapter is empty always. What I do not correctly?
public class MainActivity extends ActionBarActivity {
String TAG = "State";
static ViewPager pager;
static PagerAdapter pagerAdapter;
public static MainActivity activity;
static final int PAGE_COUNT = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
pager = (ViewPager) findViewById(R.id.pager);
pager.setOffscreenPageLimit(0);
final ArrayList<String> imagePaths = new ArrayList<String>();
imagePaths.add("http://tlt.ru/uploads/2014/05/94e1e91067997356912d68e0acc36d31_x240.jpg");
imagePaths.add("http://tlt.ru/uploads/2014/05/d2cb96bd2e26fd19c4ec5a125d8a6ada_x240.jpg");
imagePaths.add("http://tlt.ru/uploads/2014/05/6bc17baed9ef08a7aa1c68db2dcd650c_x240.jpg");
pagerAdapter = new FullScreenImageAdapter(activity, imagePaths);
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//Log.d(TAG, "onPageSelected, position = " + position);
// update();
FullScreenImageAdapter.startRefresh(imagePaths.get(position));
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
pager.setCurrentItem(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static void update() {
// pager.setAdapter(pagerAdapter);
// refreshView(pager.getCurrentItem());
pagerAdapter.notifyDataSetChanged();
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
public static TouchImageView imgDisplay;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.fragment, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imageView1);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Refresh mt = new Refresh();
try {
mt.execute(new URL(_imagePaths.get(position)));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 300);
// imgDisplay.setImageBitmap(bitmap);
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
public static void startRefresh(final String url) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Refresh mt = new Refresh();
try {
mt.execute(new URL(url));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
How I can load image in page[0]?
I thikn the problem is in the getItemPosition, try this:
#Override
public int getItemPosition (Object object){
int index = _imagePaths.indexOf(object);
if (index == -1)
return POSITION_NONE;
else
return index;
}
The problem is with the position, you can find a better solution for pager here. You need to Modify activity_main.xml to include android.support.v4.view.ViewPager in layout.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/myviewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And MainActivity.java
package com.example.androidviewpagerapp;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
public class MainActivity extends Activity {
ViewPager viewPager;
MyPagerAdapter myPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.myviewpager);
myPagerAdapter = new MyPagerAdapter();
viewPager.setAdapter(myPagerAdapter);
}
private class MyPagerAdapter extends PagerAdapter{
int NumberOfPages = 5;
int[] res = {
android.R.drawable.ic_dialog_alert,
android.R.drawable.ic_menu_camera,
android.R.drawable.ic_menu_compass,
android.R.drawable.ic_menu_directions,
android.R.drawable.ic_menu_gallery};
int[] backgroundcolor = {
0xFF101010,
0xFF202020,
0xFF303030,
0xFF404040,
0xFF505050};
#Override
public int getCount() {
return NumberOfPages;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView textView = new TextView(MainActivity.this);
textView.setTextColor(Color.WHITE);
textView.setTextSize(30);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setText(String.valueOf(position));
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(res[position]);
LayoutParams imageParams = new LayoutParams(
LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(imageParams);
LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
layout.setBackgroundColor(backgroundcolor[position]);
layout.setLayoutParams(layoutParams);
layout.addView(textView);
layout.addView(imageView);
final int page = position;
layout.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"Page " + page + " clicked",
Toast.LENGTH_LONG).show();
}});
container.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
}