First of all, I searched a lot, but the solutions are not worked, so I am here for help. the design lib used is 23.1.1
//MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<fragment
class = "com.tablayoutfragmenttest.FragmentTest"
android:id="#+id/hahah"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
// Fragment
public class FragmentTest extends Fragment {
private TabLayout mTablayout;
private ViewPager mVp;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment, container, false);
mTablayout = (TabLayout)v.findViewById(R.id.bizfrag_tabs_id);
mTablayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mVp = (ViewPager)v.findViewById(R.id.bizfrag_vp_id);
mVp.setAdapter(new MyAdapter(getChildFragmentManager()));
mVp.setOffscreenPageLimit(0);
//mTablayout.setupWithViewPager(mVp);
//mTablayout.post(new Runnable() {
// #Override
// public void run() {
// if (ViewCompat.isLaidOut(mTablayout)) {
// mTablayout.setupWithViewPager(mVp);
// } else {
// mTablayout.addOnLayoutChangeListener(
// new View.OnLayoutChangeListener() {
// #Override
// public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
// mTablayout.setupWithViewPager(mVp);
//
// mTablayout.removeOnLayoutChangeListener(this);
// }
// });
// }
// }
// });
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTablayout.post(new Runnable() {
#Override
public void run() {
mTablayout.setupWithViewPager(mVp);
}
});
}
}
//fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<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.design.widget.TabLayout
android:id="#+id/bizfrag_tabs_id"
android:layout_width="match_parent"
android:layout_height="40dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/bizfrag_vp_id"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
//ViewPager's adapter
public class MyAdapter extends FragmentStatePagerAdapter {
public static String[] totalPossibleTabs = new String[]{"this is tab0", "this is tab1", "this is tab2", "this is tab3", "this is tab4", "this is tab5", "this is tab6", "this is tab7", "this is tab8", "this is tab9"};
public MyAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
return new Fragment();
}
#Override
public int getCount() {
return totalPossibleTabs.length;
}
#Override
public CharSequence getPageTitle(int position) {
return totalPossibleTabs[position];
}
}
when I run the app, and swipe the page, the problem is as follows:
the tab's indicator is in wrong position
Try this:-
if (ViewCompat.isLaidOut(tabLayout)) {
mTablayout.setupWithViewPager(viewPager);
} else {
tabLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(...) {
mTablayout.setupWithViewPager(viewPager);
mTablayout.removeOnLayoutChangeListener(this);
}
});
}
instead of:-
mTablayout.post(new Runnable() {
#Override
public void run() {
mTablayout.setupWithViewPager(mVp);
}
});
Thank you all guys, I finally find the point,
we just cannot use
new Fragment();
in this case for simplicity,
change it to your own Fragment.
Related
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
With the help of answer of the this question in StackOverflow(Remove Fragment Page from ViewPager in Android), I successfully created my project and did some modifications according to my needs.
I am able to add N number of fragments(viewpages) in my main layout and delete them until page count becomes zero.
Now, I struck with an issue.i.e. ones, if I move from my current activity which is holding this pages to other activity or if I close my app and come back,I am only able to see initial statically added fragment.
I would like to see not only initial page but also previously added pages. Should i use SharedPreferences to store dynamically added fragments?
Here is my source code:
My main layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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="900dp"
/>
<Button
android:id="#+id/show_items"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:textColor="#ffffff"
android:background="#49a942"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="+" />
<Button
android:id="#+id/grid_apps_show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/pager"
android:layout_alignParentBottom="true"
android:text="Apps"
/>
</RelativeLayout>
My MainActivity class:
public class MainActivity extends FragmentActivity implements TextProvider{
Button home;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
private ArrayList<String> mEntries = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
home = (Button) findViewById(R.id.show_items);
mEntries.add("pos 1");
mPager = (ViewPager) findViewById(R.id.pager);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder.setTitle("Add/Delete Screens");
alertDialogBuilder
.setCancelable(false)
.setNegativeButton("+",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
addNewItem();
}
})
.setPositiveButton("-",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
removeCurrentItem();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
mAdapter = new MyPagerAdapter(this.getSupportFragmentManager(), this);
mPager.setAdapter(mAdapter);
}
private void addNewItem() {
mEntries.add("Pages");
mAdapter.notifyDataSetChanged();
}
private void removeCurrentItem() {
int position = mPager.getCurrentItem();
if(position != 0){
mEntries.remove(position);
mAdapter.notifyDataSetChanged();
}
else{
Toast.makeText(getApplicationContext(), "Minimum Screens are one!", Toast.LENGTH_LONG).show();
}
}
#Override
public String getTextForPosition(int position) {
return mEntries.get(position);
}
#Override
public int getCount() {
return mEntries.size();
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private TextProvider mProvider;
private long baseId = 0;
public MyPagerAdapter(FragmentManager fm, TextProvider provider) {
super(fm);
this.mProvider = provider;
}
#Override
public Fragment getItem(int position) {
if(position == 0){
return ScreenOne.newInstance(mProvider.getTextForPosition(position));
}
if(position == 1){
return ScreenTwo.newInstance(mProvider.getTextForPosition(position));
}
return ScreenTwo.newInstance(mProvider.getTextForPosition(position));
}
#Override
public int getCount() {
return mProvider.getCount();
}
//this is called when notifyDataSetChanged() is called
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
* #param n number of items which have been changed
*/
public void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
}
}
my fragment one:
public class ScreenOne extends Fragment {
private String mText;
public static ScreenOne newInstance(String text) {
ScreenOne f = new ScreenOne(text);
return f;
}
public ScreenOne() {
}
public ScreenOne(String text) {
this.mText = text;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.screen_one, container, false);
((TextView) root.findViewById(R.id.position_one)).setText(mText);
return root;
}
}
my fragment two:
public class ScreenTwo extends Fragment {
private String mText;
public static ScreenTwo newInstance(String text) {
ScreenTwo f = new ScreenTwo(text);
return f;
}
public ScreenTwo() {
}
public ScreenTwo(String text) {
this.mText = text;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.screen_two, container, false);
((TextView) root.findViewById(R.id.position_two)).setText(mText);
return root;
}
}
Thanks & Regards,
Aditya. J
Just override this method in FragmentpagerAdapter:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(ViewGroup container, int position, Object object);
}
And remove:
super.destroyItem(ViewGroup container, int position, Object object);
I want to create an app which swipe images left/right so i use viewPager for this i run this code it gets run successfully but blank screen comes nothing happens.
This is my homeSwipe Class
public class homeSwipe extends Activity {
ViewPager viewPager;
customPagerAdapter customPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_swipe);
viewPager = (ViewPager) findViewById(R.id.pager);
customPagerAdapter = new customPagerAdapter(homeSwipe.this);
viewPager.setAdapter(customPagerAdapter);
}
}
that is my layout.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:orientation="vertical">
<android.support.v4.view.ViewPager 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:id="#+id/pager">
</android.support.v4.view.ViewPager>
</RelativeLayout>
This is my customPagerAdapter class
public class customPagerAdapter extends PagerAdapter {
private int imgres[] ={R.drawable.graypatternbackground,R.drawable.home,R.drawable.homescreen,R.drawable.redwall};
private Context context;
private LayoutInflater layoutInflater;
public customPagerAdapter(Context context){
this.context =context;
}
#Override
public int getCount() {
return imgres.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View item_view =(View)layoutInflater.inflate(R.layout.swipelayout,container,false);
ImageView imgView = (ImageView)item_view.findViewById(R.id.imageView);
imgView.setImageResource(imgres[position]);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
This is my swipelayout.xml file
<?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">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"/>
</LinearLayout>
This is custompagerAdapter.
import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentStatePagerAdapter;public class PropTypePagerAdapter extends FragmentStatePagerAdapter { int noOfTab; public PropTypePagerAdapter(FragmentManager fm ,int noOfTab) { super(fm); this.noOfTab=noOfTab; } #Override public Fragment getItem(int position) { switch (position) { case 0: return new PropTabType(0); case 1: return new PropTabType(1); case 2: return new PropTabType(2); case 3: PropTabType service = new PropTabType(3); return service; } } #Override public int getCount() {
return noOfTab;
}
}
And this is logic for swapping image
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {view = inflater.inflate(R.layout.fragment_prop_type_tab,container, false);fragImg = (ImageView) view.findViewById(R.id.fragImg); if (position == 0) { fragImg.setImageResource(R.drawable.buy); } else if (position == 1) { fragImg.setImageResource(R.drawable.rent1); } else { fragImg.setImageResource(R.drawable.hostel); } return view; }
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;
}
So I have an FragmentActivity that have an EditText and a ListFragment.
In the ListFragment I have an adapter to populete all the items.
public class XXXListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
ArrayAdapter<Spanned> adapter = new ArrayAdapter<Spanned>(inflater.getContext(),
R.layout.fragment_list_item_appearance, spannedArray);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
With the EditText I want the user to filter the listitems.
public class XXX extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quests_activity);
EditText ediText = (EditText) findViewById(R.id.editext);
ediText .addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ListFragment.this.adapter.getFilter().filter(cs);
}
...
});
}
My problem is that I can't get the context of the Listfragment with:
ListFragment.this.adapter.getFilter().filter(cs);
The following error is thrown:
No enclosing instance of the type QuestsListFragment is accessible in
scope
Any ideas how to solve this?
Ok here the whole code. I just started to use Fragments...
FragmentActivity:
public class XXX extends FragmentActivity implements ListFragmentItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxx_activity);
}
#Override
protected void onStart() {
super.onStart();
EditText editText = (EditText) findViewById(R.id.edittext)
editText .addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// THIS DOESN'T WORK
XXXListFragment.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
#Override
public void onListFragmentItemClick(int position) {
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment prevFrag = fragmentManager.findFragmentByTag("xxx.details");
if (prevFrag != null)
fragmentTransaction.remove(prevFrag);
XXXDetailsFragment fragment = new XXXDetailsFragment();
Bundle b = new Bundle();
b.putInt("position", position);
fragment.setArguments(b);
fragmentTransaction.add(R.id.xxx_detail_fragment_container, fragment,
"xxx.details");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
...
}
}
...
}
ListFragment:
public class XXXListFragment extends ListFragment {
ListFragmentItemClickListener ifaceItemClickListener;
public interface ListFragmentItemClickListener {
void onListFragmentItemClick(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
ifaceItemClickListener = (ListFragmentItemClickListener) activity;
} catch (Exception e) {
Toast.makeText(activity.getBaseContext(), "Exception", Toast.LENGTH_SHORT).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Spanned[] xxx = { Html.fromHtml(getString(R.string.xxx)), ... };
ArrayAdapter<Spanned> adapter = new ArrayAdapter<Spanned>(inflater.getContext(),
R.layout.fragment_list_item_appearance, xxx);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
ifaceItemClickListener.onListFragmentItemClick(position);
}
}
The ListFragment is added in the FragmentActivity layout:
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical" >
...
<EditText
android:id="#+id/edittext"
style="#style/red_edittext"
android:hint="#string/exittext_input_search" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<fragment
android:id="#+id/xxx_list_fragment"
android:name="com.xxx.XXXListFragment"
android:layout_width="350dp"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="#+id/xxx_detail_fragment_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</FrameLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>
You must make a public method getAdapterOfList() in your listfragment class which will internally access the adapter and return it.