I am having some trouble with implementing OnItemClick to the ViewPager.
I would like it so when I click on one of my picture's being displayed by the ViewPager, it displays a toast message just to tell me that this is working.
So far, nothing happens when I click on one of my items when doing this.
Any help would be appreciated!
ViewPager XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/rellayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</android.support.v4.view.ViewPager>
<com.google.ads.AdView
android:id="#+id/ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="AdIdHere"
ads:loadAdOnCreate="true" >
</com.google.ads.AdView>
</RelativeLayout>
ImageDetail Fragment class:
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "extra_image_data";
private String mImageUrl;
private ImageView mImageView;
private ImageFetcher mImageFetcher;
public static ImageDetailFragment newInstance(String imageUrl) {
final ImageDetailFragment f = new ImageDetailFragment();
final Bundle args = new Bundle();
args.putString(IMAGE_DATA_EXTRA, imageUrl);
f.setArguments(args);
return f;
}
public ImageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageUrl = getArguments() != null ? getArguments().getString(
IMAGE_DATA_EXTRA) : null;
}
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
context = v.getContext();
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(context, "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (Batmanark.class.isInstance(getActivity())) {
mImageFetcher = ((Batmanark) getActivity()).getImageFetcher();
mImageFetcher.loadImage(mImageUrl, mImageView);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
ImageWorker.cancelWork(mImageView);
mImageView.setImageDrawable(null);
}
}
}
Fragment detail XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<com.question.ui.RecyclingImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="#string/imageview_description" />
</FrameLayout>
ViewPager Class:
public class Batmanark extends FragmentActivity implements OnClickListener {
private static final String IMAGE_CACHE_DIR = "images";
public static final String EXTRA_IMAGE = "extra_image";
private ImagePagerAdapter mAdapter;
private ImageFetcher mImageFetcher;
private ViewPager mPager;
#TargetApi(11)
#Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.image_detail_pager);
AdView ad = (AdView) findViewById(R.id.ad);
ad.loadAd(new AdRequest());
final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;
final int longest = (height > width ? height : width) / 2;
ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(
this, IMAGE_CACHE_DIR);
cacheParams.setMemCacheSizePercent(0.25f);
mImageFetcher = new ImageFetcher(this, longest);
mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);
mImageFetcher.setImageFadeIn(false);
mAdapter = new ImagePagerAdapter(getSupportFragmentManager(),
Images.imageUrlsBatmanark.length);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setPageMargin((int) getResources().getDimension(
R.dimen.image_detail_pager_margin));
mPager.setOffscreenPageLimit(2);
getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
if (Utils.hasHoneycomb()) {
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
mPager.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
#Override
public void onSystemUiVisibilityChange(int vis) {
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
}
});
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
actionBar.hide();
}
final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (extraCurrentItem != -1) {
mPager.setCurrentItem(extraCurrentItem);
}
}
#Override
public void onResume() {
super.onResume();
mImageFetcher.setExitTasksEarly(false);
}
#Override
protected void onPause() {
super.onPause();
mImageFetcher.setExitTasksEarly(true);
mImageFetcher.flushCache();
}
#Override
protected void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.clear_cache:
mImageFetcher.clearCache();
Toast.makeText(this, R.string.clear_cache_complete_toast,
Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
public ImageFetcher getImageFetcher() {
return mImageFetcher;
}
private class ImagePagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;
public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
return ImageDetailFragment
.newInstance(Images.imageUrlsBatmanark[position]);
}
}
#TargetApi(11)
#Override
public void onClick(View v) {
final int vis = mPager.getSystemUiVisibility();
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
}
}
you need to set click event on view in ImageDetailFragment
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
context = v.getContext();
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(context, "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
mImageView = (ImageView) v.findViewById(R.id.imageView);
return v;
}
Related
I Have a problem with getItem() function why because it is called twice in FragmentStatePagerAdapter class.
Actually the main reason is in application having TextoSpeech functionality so getItem() function twice the text also speech twice. This is my code can u please assist me....Great thanks in advance.
Here is the code
This is MainActivity class:
public class MainActivity extends FragmentActivity{
PagerFragment pagerFragment;
Cursor mCursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rhymes_activity_main);
DBUtils utils = new DBUtils(getApplicationContext());
new DBUtils(getApplicationContext());
try {
DBUtils.createDatabase();
} catch (IOException e) {
Log.w(" Create Db "+e.toString(),"===");
}
DBUtils.openDatabase();
mCursor = utils.getResult("select * from Cflviewpagerdata order by title");
final ArrayList<PageData> myList = new ArrayList<PageData>();
while (mCursor.moveToNext()) {
myList.add(new PageData(mCursor.getInt(
mCursor.getColumnIndex("_id")),
mCursor.getString(mCursor.getColumnIndex("title")),
mCursor.getString(mCursor.getColumnIndex("view"))));
}
mCursor.close();
ListView lv = (ListView) findViewById(R.id.list_view);
ListViewAdapter lva = new ListViewAdapter(this, R.layout.list_item, myList);
lv.setAdapter(lva);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//peace of code that create launch new fragment with swipe view inside
PagerFragment pagerFragment = new PagerFragment();
Bundle bundle = new Bundle();
bundle.putInt("CURRENT_POSITION", position);
bundle.putParcelableArrayList("DATA_LIST", myList);
pagerFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container, pagerFragment, "swipe_view_fragment").commit();
}
});
DBUtils.closeDataBase();
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
Fragment f = fm.findFragmentByTag("swipe_view_fragment");
if(f!=null){
fm.beginTransaction().remove(f).commit();
}else{
super.onBackPressed();
}
}
}
This is PagerFragment class:
public class PagerFragment extends Fragment{
private ArrayList<PageData> data;
private int currentPosition;
private String mTitle;
private FragmentActivity context;
#Override public void onAttach(Activity activity) {
context = (FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager, container, false);
ViewPager mViewPager = (ViewPager) v.findViewById(R.id.pager_view);
currentPosition = getArguments().getInt("CURRENT_POSITION");
mTitle = getArguments().getString("T_TITLE");
data = getArguments().getParcelableArrayList("DATA_LIST");
FragmentItemPagerAdapter fragmentItemPagerAdapter = new FragmentItemPagerAdapter(getFragmentManager(), data);
mViewPager.setAdapter(fragmentItemPagerAdapter);
mViewPager.setCurrentItem(currentPosition);
return v;
}
}
This is FragmentItemPagerAdapter class:
public class FragmentItemPagerAdapter extends FragmentStatePagerAdapter{
private static ArrayList<PageData> data;
public FragmentItemPagerAdapter(FragmentManager fm, ArrayList<PageData> data){
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putString(PageFragment.TITLE, data.get(position).getTitle());
args.putString(PageFragment.DESCRIPTION, data.get(position).getDes());
args.putInt("CURRENT_POSITION", position);
fragment.setArguments(args);
return fragment;
}
void deletePage(int position) {
if (canDelete()) {
data.remove(position);
notifyDataSetChanged();
}
}
boolean canDelete() {
return data.size() > 0;
}
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public int getCount() {
return data.size();
}
public static class PageFragment extends Fragment implements OnInitListener{
public static final String TITLE = "title";
public static final String DESCRIPTION = "view";
String om;
TextToSpeech tts;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item, container, false);
((TextView) rootView.findViewById(R.id.item_label)).setText(getArguments().getString(TITLE));
View tv = rootView.findViewById(R.id.item_des);
((TextView) tv).setText(getArguments().getString(DESCRIPTION));
Bundle bundle = getArguments();
int currentPosition = bundle.getInt("CURRENT_POSITION");
tts = new TextToSpeech( getActivity(), PageFragment.this);
om = data.get(currentPosition).getDes();
tts.speak(om, TextToSpeech.QUEUE_FLUSH, null);
return rootView;
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
tts.speak(om, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
This is PageData class:
This class is Object class
public class PageData implements Parcelable{
private String title;
private String view;
public PageData(){
}
public PageData(Parcel in){
title = in.readString();
view = in.readString();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(view);
}
public PageData(int picture, String title, String description){
this.title = title;
this.view = description;
}
public String getTitle() {
return title;
}
public String getDes() {
return view;
}
}
This is Xml code
fragment_item.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="wrap_content"
android:padding="8dp"
android:orientation="vertical">
<TextView
android:id="#+id/item_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10sp"
android:text="Image Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_gravity="center_horizontal" />
<TextView
android:id="#+id/item_des"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10sp"
android:text="Image Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
This is fragment_pager.xml: This is viewpager layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<android.support.v4.view.ViewPager
android:id="#+id/pager_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
This is rhymes_activity_main.xml: This is for listview of application.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:scrollbarAlwaysDrawVerticalTrack="true"
android:id="#+id/list_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
This images are my application look
This image is logcat of my application
Highlighted is my problem.
This is my code can you please help me any one.
I am new one of Android so please help
FragmentStatePagerAdapter preloads always at least 1 page.
You can try to use setUserVisibleHint to handle your logic only for visible fragment:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Your code
}
}
I've a ViewPager, with dots, and it's only beginning on the third slide [3/3].
But sometimes, the second slide is not showed in the ViewPager. I tried to use the Log, to show the initial position and the current position, when the position changes, and the result was: the second option is not showed, only the first and the third.
The resume of the hierarchy of my class is:
HelpHomeFragment extends BaseFragment {
ViewPagerAdapter extends PagerAdapter {}
HelpFrag1 extends Fragment {}
HelpFrag2 extends Fragment {}
HelpFrag3 extends Fragment {}
}
and my code is below:
HelpHomeFragment.java
public class HelpHomeFragment extends BaseFragment {
#BindView(R.id.llt_help_tipsbase)
LinearLayout llTips;
#BindView(R.id.vpg_help)
ViewPager viewPager;
#BindView(R.id.slider_dots)
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
private static final String ARG_PARAM1 = "Title";
private DataManager dm;
private HelpHomeFragmentPresenter<HelpHomeFragment> presenter;
private ListHelpsAdapter listHelpsAdapter;
private MyTimerTask mtt;
public static Fragment newInstance(String title) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, title);
Fragment fragment = new HelpHomeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dm = ((MvpApp) getActivity().getApplication()).getDataManager();
presenter = new HelpHomeFragmentPresenter<>(dm);
presenter.onAttach(this);
}
#Override
public void onResume() {
super.onResume();
showSlideshowTips();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_help_home, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void showSlideshowTips() {
configSlideshow();
}
#Override
public void configSlideshow() {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for (int i = 0; i < dotscount; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotscount; i++)
dots[i].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.nonactive_dot));
dots[position].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
try {
mtt = new MyTimerTask();
new Timer().scheduleAtFixedRate(mtt, 4500, 9000);
} catch (Exception e) {
e.printStackTrace();
}
}
// CUSTOM TIMER
class MyTimerTask extends TimerTask {
#Override
public void run() {
try {
getBaseActivity().runOnUiThread(() -> {
if (viewPager.getCurrentItem() == 0) {
viewPager.setCurrentItem(1);
} else if (viewPager.getCurrentItem() == 1) {
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
// CUSTOM PAGE ADAPTER
class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
Fragment[] fragments = {new HelpFrag1(), new HelpFrag2(), new HelpFrag3()};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = null;
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.custom_layout, null);
try {
View finalView = view;
getActivity().runOnUiThread(() -> getActivity().getSupportFragmentManager().beginTransaction()
.replace(finalView.getId(), fragments[position], "findThisFragment")
.addToBackStack(null).commit());
} catch (Exception e){
e.printStackTrace();
}
}
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
// classes fragment for the slideshow. Each fragment is an slide
public static class HelpFrag1 extends Fragment {
public HelpFrag1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_help_frag1, container, false);
}
}
// and more two classes HelpFrag, only changing the end (HelpFrag2 and HelpFrag3)
// and changing the layout to fragment_help_frag2 and fragment_help_frag3
}
and my layout base of the ViewPager is:
fragment_help_home.xml
<!-- another tag -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/vpg_help"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:paddingTop="4dp"
android:layout_marginRight="30dp"
android:overScrollMode="never" />
<LinearLayout
android:id="#+id/slider_dots"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="-20dp"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal" />
</LinearLayout>
<!-- another tag -->
After updating to the support repository,
compile('com.android.support:support-v4:26.+') {
force = true
}
compile('com.android.support:appcompat-v7:26.+') {
force = true
}
compile('com.android.support:design:26.+') {
force = true
}
compile('com.android.support:cardview-v7:26.+') {
force = true
}
compile('com.android.support:recyclerview-v7:26.+') {
force = true
}
I'm getting this weird exception.
TransactionDetailsFragment must be a public static class to be properly recreated from instance state
Here is a my source code
public class TransactionDetailsViewFragment extends MainFragment implements FragmentWithKeepPrevious, FragmentWithName, FragmentWithBackAction {
private ViewPager mViewPager;
private PagerTitleStrip mPagerTitleStrip;
private View mView;
private int transaclionPosition;
private List<Transaction> cashTransactions;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_transaction_details_view, container, false);
mViewPager = mView.findViewById(R.id.u_transaction_details_viewpager_3);
mPagerTitleStrip = mView.findViewById(R.id.u_transaction_details_header);
try {
cashTransactions = new ArrayList<>();
if (GlobalClassParameters.transactions != null) {
cashTransactions = GlobalClassParameters.transactions;
}
} catch (ClassCastException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
if (cashTransactions != null)
mViewPager.setAdapter(new ScreenSlidePagerAdapter(getChildFragmentManager()));
mPagerTitleStrip.setTextColor(Color.parseColor("#ffffff"));
Bundle bundle = this.getArguments();
if (bundle != null) {
transaclionPosition = bundle.getInt("transactionPosition");
mViewPager.setCurrentItem(transaclionPosition);
}
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
try {
mViewPager.setCurrentItem(position);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return mView;
}
void syncTitles() {
for (int counter = 0; counter < mPagerTitleStrip.getChildCount(); counter++) {
if (mPagerTitleStrip.getChildAt(counter) instanceof TextView) {
TextView textView = ((TextView) mPagerTitleStrip.getChildAt(counter));
UniPAYTypefaceUtils.setLocalisation(textView, getActivity(), TextStyle.LIGHT);
textView.setTextSize(14);
}
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
TransactionDetailsFragment transactionDetailsFragment = new TransactionDetailsFragment();
transactionDetailsFragment.setTransaction(cashTransactions.get(position).getTransactionDetails().getTransactionView());
transactionDetailsFragment.setTransactionButtons(cashTransactions.get(position).getTransactionDetails().getTransationButton());
transactionDetailsFragment.setmTransactionPosition(position);
syncTitles();
return transactionDetailsFragment;
}
#Override
public int getCount() {
return cashTransactions.size();
}
#Override
public CharSequence getPageTitle(int position) {
String title = cashTransactions.get(position).getName();
SpannableString whiteSpannable = new SpannableString(title);
return whiteSpannable;
}
}
#Override
public boolean onBack() {
transaclionPosition = 0;
return true;
}
#Override
public int getName() {
return R.string.u_transaction_details;
}
#Override
public Class getBackFragment() {
transaclionPosition = 0;
return HistoryFragment.class;
}
public class TransactionDetailsFragment extends Fragment {
private List<KeyValueParams> mTransaction;
private List<TransationButton> transationButtons;
private int mTransactionPosition = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.view_transaction_details, container, false);
CustomRecyclerView listView = view.findViewById(R.id.u_transaction_details);
if (mTransaction != null) {
final KeyValueRecyclerViewAdapter keyValueAdapter = new KeyValueRecyclerViewAdapter(getActivity(), mTransaction);
listView.setAdapter(keyValueAdapter);
listView.setLayoutManager(new LinearLayoutManager(getActivity()));
keyValueAdapter.notifyDataSetChanged();
}
((TextView) view.findViewById(R.id.t_datetime)).setText(cashTransactions.get(mTransactionPosition).getDatetime());
return view;
}
public void setTransaction(List<KeyValueParams> mTransaction) {
this.mTransaction = mTransaction;
}
public void setTransactionButtons(List<TransationButton> transactionButtons) {
this.transationButtons = transactionButtons;
}
public void setmTransactionPosition(int position) {
this.mTransactionPosition = position;
}
}
}
As you can see, I'm using ViewPager and and PagerTitleStrip inside Viewpager. Here is my xml code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff"
android:clickable="true">
<LinearLayout
android:id="#+id/u_header"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/u_transaction_details_viewpager_3"
android:layout_width="fill_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTitleStrip
android:id="#+id/u_transaction_details_header"
android:layout_width="fill_parent"
android:layout_height="48dp"
android:layout_gravity="top"
android:paddingLeft="#dimen/u_common_margin_left"
android:paddingRight="#dimen/u_common_margin_right"
android:background="#color/u_pink_light"
android:padding="#dimen/u_common_text_size_small"
android:textAlignment="center" />
</android.support.v4.view.ViewPager>
</LinearLayout>
</LinearLayout>
When I try to go my Fragment,I have this exception
Can anyone tell me what's wrong in my source or how I can write my code to can run without exceptions in new support library?
You should make TransactionDetailsFragment an entirely separate Java file, or make it a public static class, as the error says.
This has nothing to do with your Gradle dependencies, although you honestly should avoid using a + in any dependency
how can I can access in this example the object "selectedBox" from the fragment? I need it in the main activity for testing connection and in the fragment.
In the moment I create it in the main and the fragment.
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener{
private ViewPager viewPager;
private ActionBar actionBar;
private MainTabAdapter mAdapter;
private String[] tabs = { "Live" };
private box selectedBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new MainTabAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
selectedBox = new box(this);
}
public void onResume(){
super.onResume();
if(selectedBox.getId() != -1){
checkReachable(selectedBox.getIpPort());
}else {
Intent intent = new Intent(this, SettingsActivity.class);
this.startActivity(intent);
finish();
}
}
private void checkReachable(String ipPort) {
Log.d("XML Request", "CHECK BOX");
String e2About = "http://" + ipPort + "/web/about";
getXml.DownloadCompleteListener dcl = new getXml.DownloadCompleteListener() {
#Override
public void onDownloadComplete(String result) {
if (!result.contains("<e2enigmaversion>")) {
Toast.makeText(getApplicationContext(), "Active box not reachable.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
}else{
viewPager.setAdapter(mAdapter);
}
}
};
getXml downloader = new getXml(dcl);
downloader.execute(e2About);
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainTabAdapter
public class MainTabAdapter extends FragmentPagerAdapter {
public MainTabAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new MainFragmentLive();
}
return null;
}
#Override
public int getCount() {
return 1;
}
}
MainFragmentLive.java
public class MainFragmentLive extends ListFragment {
private box selectedBox;
private List<String> bouquetListString;
private ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_live, container, false);
Log.d("Position", "Main Live Set Box");
selectedBox = new box(getActivity());
bouquetListString = selectedBox.getBouquets().get(2);
if(bouquetListString.size() < 1){
getBouquetBox();
}
adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, bouquetListString);
setListAdapter(adapter);
ImageButton reloadBouquet = (ImageButton) view.findViewById(R.id.reloadBouquet);
reloadBouquet.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
getBouquetBox();
}
});
setHasOptionsMenu(true);
return view;
}
public void onListItemClick(ListView l, View v, int position, long id) {
SharedPreferences savedData = getActivity().getSharedPreferences("box",0);
SharedPreferences.Editor editor = savedData.edit();
editor.putInt("boId", position);
editor.apply();
Intent gotoChannels = new Intent(getActivity(), ChannelListActivity.class);
startActivity(gotoChannels);
}
public void getBouquetBox(){
getXml.DownloadCompleteListener dcl = new getXml.DownloadCompleteListener() {
#Override
public void onDownloadComplete(String result) {
selectedBox.delBouquets();
bouquetListString.clear();
String [] tags = {"e2servicereference", "e2servicename"};
List<List<String>> bouquetsList = parseXml.parseXmlByTag(result, tags);
selectedBox.addBouquets(bouquetsList);
bouquetListString.addAll(selectedBox.getBouquets().get(2));
adapter.notifyDataSetChanged();
}
};
Log.d("XML Request", "GET BOUQUET");
getXml downloader = new getXml(dcl);
downloader.execute("http://" + selectedBox.getIpPort() + "/web/getservices");
}
}
activity_main.xml
<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_parent">
</android.support.v4.view.ViewPager>
fragment_main_live.xml
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="8dp">
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:text="#string/selectBouquet"
style="#style/header1"/>
<ImageButton
android:layout_width="0dip"
android:layout_height="wrap_content"
android:id="#+id/reloadBouquet"
android:src="#drawable/ic_action_refresh"
android:contentDescription="#string/search"
android:layout_weight=".20"
android:layout_gravity="bottom"/>
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/list" />
</LinearLayout>
You need to create an interface to your activity from your fragment. Something like:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener,MainFragment.getSelectedBox {
private ViewPager viewPager;
private ActionBar actionBar;
private MainTabAdapter mAdapter;
private String[] tabs = { "Live" };
private box selectedBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
}
//called from the MainFragment
#Override
public void AccessSelectedBox {
this.box = <do something with box>
}
}
Fragment Class
public class MainFragment extends ListFragment {
//interface to the MainActivity activity class
private getSelectedBox listener;
public interface getSelectedBox {
public void AccessSelectedBox();
}
}
Here is a good article on this: http://www.vogella.com/articles/AndroidFragments/article.html.
I have set up my app to load lots of images/wallpapers from an external source/link then load those images into view so the user can scroll through them.
I am wanting to make it so once the user clicks on the image they have in view, it will then set is as their wallpaper.
Here's my class:
public class Question extends FragmentActivity implements OnClickListener {
private static final String IMAGE_CACHE_DIR = "images";
public static final String EXTRA_IMAGE = "extra_image";
private ImagePagerAdapter mAdapter;
private ImageFetcher mImageFetcher;
private ViewPager mPager;
#TargetApi(11)
#Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.image_detail_pager);
AdView ad = (AdView) findViewById(R.id.ad);
ad.loadAd(new AdRequest());
final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;
final int longest = (height > width ? height : width) / 2;
ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(
this, IMAGE_CACHE_DIR);
cacheParams.setMemCacheSizePercent(0.25f);
mImageFetcher = new ImageFetcher(this, longest);
mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);
mImageFetcher.setImageFadeIn(false);
mAdapter = new ImagePagerAdapter(getSupportFragmentManager(),
Images.imageUrlsQuestion.length);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setPageMargin((int) getResources().getDimension(
R.dimen.image_detail_pager_margin));
mPager.setOffscreenPageLimit(2);
getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
if (Utils.hasHoneycomb()) {
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
mPager.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
#Override
public void onSystemUiVisibilityChange(int vis) {
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
}
});
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
actionBar.hide();
}
final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (extraCurrentItem != -1) {
mPager.setCurrentItem(extraCurrentItem);
}
}
#Override
public void onResume() {
super.onResume();
mImageFetcher.setExitTasksEarly(false);
}
#Override
protected void onPause() {
super.onPause();
mImageFetcher.setExitTasksEarly(true);
mImageFetcher.flushCache();
}
#Override
protected void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.clear_cache:
mImageFetcher.clearCache();
Toast.makeText(this, R.string.clear_cache_complete_toast,
Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
public ImageFetcher getImageFetcher() {
return mImageFetcher;
}
private class ImagePagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;
public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
return ImageDetailFragment
.newInstance(Images.imageUrlsQuestion[position]);
}
}
#TargetApi(11)
#Override
public void onClick(View v) {
final int vis = mPager.getSystemUiVisibility();
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
}
}
Take a look in Set Wallpaper using WallpaperManager here
and don't forget to add the below permission to your Manifest:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>