I have a ViewPager that I set up in a simple example app. I have a single static fragment implemented as an inner-class with a RecylerView in it. I'd like to change the LayoutManager of the RecyclerView based on which tab I'm in. My implementation is show below. This is not working for me. When I load this ViewPager is starts in the 1st position but has a staggered layout (which should be for the 3rd position). When I swipe over to the 2nd position it is still the staggered layout, nothing changed as the getItem() method of my PagerAdapter was never called. When I switch over to the 3rd position is does call getItem() and the RecylerView is reloaded, however it still has the staggered layout (this is where it actually should have the staggered layout).
After reading up a bit on ViewPagers I'm realizing that the PagerAdapter will reuse the fragment if it determines that it can. I think that is what is happening here. Is there any way to keep this from happening? Can I get my LayoutManager to switch for each tab while just using one Fragment? Essentially I want it to instantiate a new Fragment for each tab.
public class TabbedActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
public static Intent newIntent(Context packageContext){
Intent intent = new Intent(packageContext, TabbedActivity.class);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_tabbed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class RecyclerFragment extends Fragment {
private static final String ARG_LAYOUT_TYPE = "layout-type";
private int layoutType = 0;
RecyclerView recyclerView;
public ArrayList<AndroidVersion> data;
public DataAdapter adapter;
public static final int FRAGMENT_LINEAR = 0;
public static final int FRAGMENT_GRID = 1;
public static final int FRAGMENT_STAG_GRID = 2;
public static RecyclerFragment newInstance(int layoutType) {
Timber.d("newInstance() called with int: " + layoutType);
RecyclerFragment fragment = new RecyclerFragment();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_TYPE, layoutType);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(getArguments() != null){
layoutType = getArguments().getInt(ARG_LAYOUT_TYPE);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_linear, container, false);
Button button = (Button) rootView.findViewById(R.id.view_pager_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mainActivityIntent = MainActivity.newIntent(getActivity().getApplicationContext());
startActivity(mainActivityIntent);
}
});
recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recyler_view_pager);
//recyclerView.setHasFixedSize(true);
// Check to see what the layout type should be and create the necessary LayoutManager
switch(layoutType){
case FRAGMENT_LINEAR:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
case FRAGMENT_GRID:
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(gridLayoutManager);
case FRAGMENT_STAG_GRID:
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
}
loadJSON();
return rootView;
}
private void loadJSON() {
Retrofit retrofit = MainActivity.getRestAdapter();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getAndroid()));
adapter = new DataAdapter(data);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
Timber.d("getItem called, position: " + position);
return RecyclerFragment.newInstance(position);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Linear";
case 1:
return "Grid";
case 2:
return "Staggered";
}
return null;
}
}
}
Try this :
inside the RecyclerFragment class define a static variable :
private static RecyclerFragment instance = null;
and change newInstance method like below :
public static RecyclerFragment newInstance(int layoutType) {
Timber.d("newInstance() called with int: " + layoutType);
instance =new RecyclerFragment();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_TYPE, layoutType);
instance.setArguments(args);
return instance;
}
Related
First of all, I'm sorry for my english, but I need your help.
I got a recyclerView gallery with photos and option to show the selected photo in another activity.
I`m trying to share an image that activity to somewhere, e.g. email, but I receive an empty message with no image.
Could you help me to find out, what am I doing wrong?
Below is the code of gallery activity and single image activity.
Thank you for answers.
public class MainActivity extends AppCompatActivity {
GalleryAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<ImageModel> data = new ArrayList<>();
public static String getURLForResource(int resourceId) {
return Uri.parse("android.resource://" + R.class.getPackage().getName() + "/" + resourceId).toString();
}
public static String IMGS[];
public static String MAYF[] = {
"file:///android_asset/mayf1.jpg",
"file:///android_asset/mayf2.gif",
"file:///android_asset/mayf3.jpg",
"file:///android_asset/mayf4.jpg",
"file:///android_asset/mayf5.gif",
"file:///android_asset/mayf6.gif",
"file:///android_asset/mayf7.jpg",
"file:///android_asset/mayf8.jpg",
"file:///android_asset/mayf9.jpg",
"file:///android_asset/mayf10.jpg"
};
public static String APRF[] = {
"file:///android_asset/apr1.jpg",
"file:///android_asset/apr2.gif",
"file:///android_asset/apr3.jpg",
"file:///android_asset/apr4.jpg",
"file:///android_asset/apr5.gif",
"file:///android_asset/apr6.gif",
"file:///android_asset/apr7.jpg",
"file:///android_asset/apr8.jpg",
"file:///android_asset/apr9.jpg",
"file:///android_asset/apr10.jpg"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (StartingActivity.count == 1)
IMGS = Arrays.copyOf(APRF, APRF.length);
else if (StartingActivity.count == 2) {
IMGS = Arrays.copyOf(MAYF, MAYF.length);
} else {
Toast.makeText(getBaseContext(), "not filled yet",
Toast.LENGTH_LONG).show();
}
for (int i = 0; i < IMGS.length; i++) {
ImageModel imageModel = new ImageModel();
imageModel.setName("Image " + i);
imageModel.setUrl(IMGS[i]);
data.add(imageModel);
}
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
intent.putExtra("superUri", IMGS[position]);
startActivity(intent);
}
}));
}
#Override
public void onBackPressed() {
super.onBackPressed();
StartingActivity.count = 0;
}
}
This part is a part of a single image.
public class DetailActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private ShareActionProvider mShareActionProvider;
public ArrayList<ImageModel> data = new ArrayList<>();
int pos;
String shPos;
Toolbar toolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
// setSupportActionBar(toolbar);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
shPos = getIntent().getStringExtra("superUri");
setTitle("Открытки");
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
//setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#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_detail, menu);
// Fetch and store ShareActionProvider
// Return true to display menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void onShClick(MenuItem item) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(shPos));
shareIntent.setType("image/*");
startActivity(shareIntent);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageModel> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageModel> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUri());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
#Override
public CharSequence getPageTitle(int position) {
return data.get(position).getName();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
final ImageView imageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).into(imageView);
return rootView;
}
}
}
Here is an example of trying to share image via gmail. I can see the image "attached", but can`t open it. Another email receives an empty message with no attachment inside.
sharing example
From MainActivity when i goto HolidayActivity by using explicit intent i am able to see the LisView is populated with distinct elements within the fragment, After pressing back button i again goto MainActivity and when i again try to open HolidayActivity the ListView is populated again with duplicate elements, I have used LoaderManager, so when device is rotated there is no duplicate elements, the problems occurs only when i switch between activities as described above. I have also tried to Override methos onKeyDown() and onBackPresses() but nothing seems to work out. Point to be noted out here is that i am fetching the list items from server.
HolidayActivity.java
public class HolidaysActivity extends AppCompatActivity {
public static String HOLIDAY_REQUEST_URL;
public static holidayAdapter adapter;
public static final String LOG_TAG = HolidaysActivity.class.getSimpleName();
public static Context mcontext ;
public static Activity activity = null;
public static int list_id;
public static ListView listView_holiday;
/**
* The {#link PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link FragmentStatePagerAdapter}.
*/
private static boolean studentLogin = false;
private static boolean employeeLogin = false;
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
mcontext = this;
activity = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holidays);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
HolidaysActivity.this.finish();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
super.onBackPressed();
activity.finish();
}
#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_holidays, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<holidays>> {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.holidays_list, container, false);
// condition for switching to student login in TabWidget for registering complain
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
HOLIDAY_REQUEST_URL = "http://192.168.43.26/fetch_restricted_holidays.php";
listView_holiday = (ListView)rootView.findViewById(R.id.list);
adapter = new holidayAdapter(activity,new ArrayList<holidays>(),0);
listView_holiday.setAdapter(adapter);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(1,null,this);
}
//condition for switching to employee login in Tabwidget for registering complain
else {
}
return rootView;
}
#Override
public Loader<List<holidays>> onCreateLoader(int id, Bundle args) {
return new HolidayLoader(activity,HOLIDAY_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<holidays>> loader, List<holidays> holidays) {
adapter.clear();
if(holidays!=null && !holidays.isEmpty()){
adapter.addAll(holidays);
adapter.notifyDataSetChanged();
}
}
#Override
public void onLoaderReset(Loader<List<holidays>> loader) {
adapter.clear();
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Gazetted Holidays";
case 1:
return "Restricted Holidays";
}
return null;
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout complainLinearLayout = (LinearLayout)findViewById(R.id.complain_LinearLayout);
complainLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent complainIntent = new Intent(MainActivity.this, Complain.class);
startActivity(complainIntent);
}
});
LinearLayout holiday = (LinearLayout)findViewById(R.id.holidays_LinearLayout);
holiday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity( new Intent(MainActivity.this, HolidaysActivity.class));
}
});
}
}
I am trying to make my tabbed activity content to change dynamically, depended on the user choices in the other tabs.
All tabs are using the same fragment. only the content in the view is supposed to change (in this case a ListView)
Now the main problem is that when I make a choice (click on some line in the ListView) the next tab shows all of the content instead of filtering the data according to my choice in the previous tab, though when I click on a not-neighbor tab and then go back, the tab is filtered like I wanted.
From what I understand, the activity load the neighbor tabs of the current tab even if those are not focused and this is why I get the default result.
To simplify things:
Then I choose some line from the ListView and the focus automatically goes to the next tab.
The listView will show me the default contet, as if I chose nothing. But if I move the focus to the forth tab, and then again back to the second, the listView will be filtered as I wanted
Here is my code
public class Catalog_actbartabs extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
public static String PACKAGE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog_actbartabs);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
PACKAGE_NAME = getApplicationContext().getPackageName();
}
public void setCurrentItem(int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
#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_catalog_actbartabs, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
protected ClogListAdapter2 clogListAdapter2;
protected ArrayList<String[]> stringArrayList;
protected static String topic = null;
protected static String rName = null;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String EXTRA_ITEM_INFO = "com.dstudio.dvir.EXTRA_ITEM_INFO";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
rootView = inflater.inflate(R.layout.fragment_catalog, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
try {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
stringArrayList = Utils.getNamesList(super.getContext());
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
stringArrayList = Utils.getTopicsList(super.getContext(), rName);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3)
stringArrayList = Utils.getClassesList(super.getContext(), rName, topic);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4)
stringArrayList = Utils.getFilesList(super.getContext());
} catch (Throwable t) {
Toast.makeText(super.getContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
if (savedInstanceState != null) {
String[] values = savedInstanceState.getStringArray("myKey");
if (values != null) {
stringArrayList = ClogListAdapter2.bmListFromArray(values);
}
} else if (stringArrayList == null) {
stringArrayList = new ArrayList<String[]>();
}
clogListAdapter2 = new ClogListAdapter2(super.getContext(), stringArrayList, getArguments().getInt(ARG_SECTION_NUMBER));
ListView listV = (ListView) rootView.findViewById(R.id.listView);
listV.setAdapter(clogListAdapter2);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
rName = null;
else rName = clogListAdapter2.getItem(position)[0];
topic = null;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
topic = null;
else topic = clogListAdapter2.getItem(position)[0];
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
Intent intent = new Intent(parent.getContext(), AudioPlayerActivity.class);
intent.putExtra(EXTRA_ITEM_INFO, clogListAdapter2.getItem(position));
startActivityForResult(intent, 1);
}
((Catalog_actbartabs) getActivity()).setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER), true);
}
});
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "page 1";
case 1:
return "page 2";
case 2:
return "page 3";
case 3:
return "page 4";
}
return null;
}
}
}
UPDATE
Working Solution From #AmeyShirke
I added the var _hasLoadedOnce= false; to the rest of the vars in PlaceholderFragment class:
public static class PlaceholderFragment extends Fragment {
protected ClogListAdapter2 clogListAdapter2;
protected ArrayList<String[]> stringArrayList;
protected View rootView;
protected static String topic = null;
protected static String rName = null;
private boolean _hasLoadedOnce= false;
//Rest of the code
}
Now All the data setting code is inside setUserVisibleHint() without changing _hasLoadedOnce so it look like this:
#Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
// we check that the fragment is becoming visible
if (isFragmentVisible_ && !_hasLoadedOnce) {
Log.i("visable: ", getArguments().getInt(ARG_SECTION_NUMBER)+"");
try {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
stringArrayList = Utils.getNamesList(super.getContext());
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
stringArrayList = Utils.getTopicsList(super.getContext(), rName);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3)
stringArrayList = Utils.getClassesList(super.getContext(), rName, topic);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4)
stringArrayList = Utils.getFilesList(super.getContext());
} catch (Throwable t) {
Toast.makeText(super.getContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
clogListAdapter2 = new ClogListAdapter2(super.getContext(), stringArrayList, getArguments().getInt(ARG_SECTION_NUMBER));
ListView listV = (ListView) rootView.findViewById(R.id.listView);
listV.setAdapter(clogListAdapter2);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: 23/12/2016 remember to also give the needed info to get the asked next category
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
rName = null;
else rName = clogListAdapter2.getItem(position)[0];
topic = null;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
topic = null;
else topic = clogListAdapter2.getItem(position)[0];
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
Intent intent = new Intent(parent.getContext(), AudioPlayerActivity.class);
intent.putExtra(EXTRA_ITEM_INFO, clogListAdapter2.getItem(position));
startActivityForResult(intent, 1);
}
((Catalog_actbartabs) getActivity()).setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER), true);
}
});
//Notify that _hasLoadedOnce = true; is now gone
}
}
}
I also added the line mViewPager.setOffscreenPageLimit(3); in the activity's onCreate() because if I chose to go directly to the forth tab after the first filtering it wouldn't filter it, so that way the activity will filter it correctly.
This is default behaviour of ViewPager. To load only single tab use:
mViewPager.setOffscreenPageLimit(1);
If that doesnt work, then you have to create your own sub-class of ViewPager and override the below method:
private boolean _hasLoadedOnce= false; // your boolean field
#Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
// we check that the fragment is becoming visible
if (isFragmentVisible_ && !_hasLoadedOnce) {
//your code here
_hasLoadedOnce = true;
}
}
}
I'm using tabbed activity to show three tabs
the problem is, the first tab is always blank, while the second and third works. and if i click the third one and after that click on the first one, the first loads the data
public class Main2Activity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public static class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a Movies_Fragment (defined as a static inner class below).
Movies_Fragment fragment = Movies_Fragment.newInstance(position );
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Most Popular";
case 1:
return "Top Rated";
case 2:
return "Top Rated 2";
}
return null;
}
}
}
public class Movies_Fragment extends Fragment {
public static ImageAdapter imageAdapter;
public static Movies_Fragment newInstance(int sectionNumber) {
Movies_Fragment fragment = new Movies_Fragment();
Bundle args = new Bundle();
args.putInt("index", sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart() {
super.onStart();
updateMovies();
//imageAdapter.notifyDataSetChanged();
}
public void updateMovies() {
FetchMovieTask movieTask = new FetchMovieTask();
Bundle bundle = getArguments();
int index = bundle.getInt("index");
movieTask.execute(index);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies_, container, false);
imageAdapter = new ImageAdapter(getActivity());
GridView gridView = (GridView)rootView.findViewById(R.id.gridView);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MDMovie movie = (MDMovie) imageAdapter.getItem(i);
Intent intent = new Intent(getActivity(),movieDetailsActivity.class);
intent.putExtra("movie", movie);
startActivity(intent);
}
});
return rootView;
}
}
This happened to one of my projects also and I was unable to diagnose it then too. I ended up using this [dirty] hack. Its not a solution by far but, it worked for us. We basically simulate a page change on start:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
mViewPager.setCurrentItem(0);
}
I am a beginner to android applications,I working around tab+swipe application,
my main class is like belove. please help me out.
public class MainScreenViewActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
private static String list_display_data1 = "item#sec1";
private static String list_display_data2 = "item#sec2";
private static String list_display_data3 = "item#sec3";
private static View rootView;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen_view);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
/*mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});*/
}
#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_screen_view, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(
R.layout.fragment_main_screen_view_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
dummyTextView.setVisibility(View.INVISIBLE);
if(dummyTextView.getVisibility() == View.VISIBLE){
ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
}
else{
Log.d("", "");
}
//ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
//initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
return rootView;
}
}
public static void initListView(Context context, ListView listView,String prefix, int numItems, int layout ){
// By using setAdpater method in listview we an add string array in list.
String[] arr = new String[numItems];
for(int i = 0; i< arr.length; i++){
arr[i] = prefix + (i +1);
}
listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Context context = view.getContext();
String msg = "item[" + position + "]= " + parent.getItemIdAtPosition(position);
Toast.makeText(context, msg, 1000).show();
System.out.println(msg);
}
});
}
}
in onCreateView of dummySectionFragment how to add different list view. I just able to work on visibility of view.
You should Add Fragments to your viewpager for different page for different Tabs.