I am using TabLayout to show three tabs and on selection of each am calling FragmentTransaction.replace method. Now my problem is that the first two fragments are correctly replaced but the third fragment in particular is not getting replaced though I debugged and found that all corresponding methods of the 3rd fragments are called and there is no error. Now am out of my wits, please help!!.
This is the code in my onCreate() method of my main activity from where i am showing the three tabs.
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Explore"));
tabLayout.addTab(tabLayout.newTab().setText("Me"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
HomeTabFragment htf = new HomeTabFragment();
transaction.replace(R.id.tab_content_fragment, htf);
transaction.commit();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if (position == 0) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
HomeTabFragment htf = new HomeTabFragment();
transaction.replace(R.id.tab_content_fragment, htf);
//transaction.commitAllowingStateLoss();
transaction.addToBackStack(null);
transaction.commit();
} else if (position == 1) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
ItemListFragment ilf = new ItemListFragment();
transaction.replace(R.id.tab_content_fragment, ilf);
//transaction.commitAllowingStateLoss();
transaction.addToBackStack(null);
transaction.commit();
} else if (position == 2) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
MeTabFragment meTabFragment = new MeTabFragment();
transaction.replace(R.id.tab_content_fragment, meTabFragment);
transaction.addToBackStack(null);
transaction.commit();
//transaction.commitAllowingStateLoss();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
And this is my MeTabFragment...
public class MeTabFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private DisplayDensity display;
private int profilePicSizeInPx;
private final float percentageOfScreenHeightOfProfilePic = 0.15f;
private CheckInternetConnection connection;
private ImageView userProfilePic;
private TextView userName;
private ProgressBar profilePicPB;
private String personPhotoUrl;
private String PROFILE_PIC_SIZE = "400";
private SharedPreferences sPrefs;
private SharedPreferences.Editor editor;
ListView m_homeOfferLV = null;
MeTabAdapter m_meTabAdapter = null;
ArrayList<MeData> m_ArrayList;
private GoogleApiClient mGoogleApiClient;
// Creating a listener interface to communicate back to the calling activity
//OnLogOutButtonClickListener mCallback;
private Analytics analytics;
private Tracker t;
// Container Activity must implement this interface
public static MeTabFragment newInstance() {
MeTabFragment fragment = new MeTabFragment();
//fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
analytics = new Analytics(getActivity(),getActivity().getString(R.string.MeTabFragment));
t = analytics.getTrackerInstance();
}
#Override
public void onResume() {
super.onResume();
if(Analytics.analytics_enabled && Analytics.lastTabStripPositionValue==2)
t.send(new HitBuilders.ScreenViewBuilder().build());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sPrefs = getActivity().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
editor = sPrefs.edit();
mGoogleApiClient = ApiClientGoogle.mApiClientGoogle;
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
connection = new CheckInternetConnection(getActivity());
display = new DisplayDensity(getActivity());
profilePicSizeInPx = (int) (percentageOfScreenHeightOfProfilePic * (float) display.getScreenHeightInPixels());
//mAnalytics = new Analytics(getActivity(),"Me");
return inflater.inflate(R.layout.fragment_me_tab, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
m_homeOfferLV = (ListView) view.findViewById(R.id.me_tab_list_view);
userProfilePic = (ImageView) view.findViewById(R.id.profile_pic);
userName = (TextView) view.findViewById(R.id.user_name_tv);
userProfilePic.getLayoutParams().height = profilePicSizeInPx;
userProfilePic.getLayoutParams().width = profilePicSizeInPx;
tracker.send(new HitBuilders.EventBuilder()
.setCategory("MeScreen")
.setAction("click")
.setLabel("Me")
.build());*/
userName.setText(sPrefs.getString(getString(R.string.user_name), "User Name"));
personPhotoUrl = sPrefs.getString(getString(R.string.user_profile_pic_url), null);
if (sPrefs.getBoolean(getString(R.string.is_google_logged_in), false) && personPhotoUrl != null) {
personPhotoUrl = personPhotoUrl.substring(0, personPhotoUrl.length() - 2) + PROFILE_PIC_SIZE;
}
//if user is connected to internet and has profile pic url then fetch the url and show his profile pic.
if (personPhotoUrl != null && connection.isConnectedToInternet()) {
//show progress bar till the image is fetched and don't show the profile pic for now.
profilePicPB.setVisibility(View.VISIBLE);
new LoadProfileImage(userProfilePic).execute(personPhotoUrl);
} else {
//show default pic only and set progress bar visiblity to null.
Log.v("Debug", "Profile pic url is null");
profilePicPB.setVisibility(View.INVISIBLE);
}
m_ArrayList = new ArrayList<MeData>();
MeData meData = new MeData();
meData.mPageRank = 1;
meData.mTitle = "My Collections";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 2;
meData.mTitle = "My Offers";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 3;
meData.mTitle = "My Store List";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 4;
meData.mTitle = "Settings";
meData.mDetail="";
m_ArrayList.add(meData);
//adding an empty item in the list to draw the bottom border.
meData = new MeData();
meData.mPageRank = 5;
meData.mTitle = "";
meData.mDetail="";
m_ArrayList.add(meData);
m_meTabAdapter = new MeTabAdapter(getActivity(), R.layout.fragment_me_tab_template, m_ArrayList);
m_homeOfferLV.setAdapter(m_meTabAdapter);
m_homeOfferLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (m_ArrayList.get(position).mPageRank == 1) {
Intent i = new Intent(getActivity(), MyProductsActivity.class);
getActivity().startActivity(i);
} else if (m_ArrayList.get(position).mPageRank == 2) {
Intent i = new Intent(getActivity(), MyOffersActivity.class);
getActivity().startActivity(i);
} else if (m_ArrayList.get(position).mPageRank == 3) {
if (connection.isConnectedToInternet()) {
Intent i = new Intent(getActivity(), MyStoresActivity.class);
getActivity().startActivity(i);
} else {
Toast.makeText(getActivity(), getActivity().getString(R.string.check_internet_connection_try_again), Toast.LENGTH_SHORT).show();
}
}else if (m_ArrayList.get(position).mPageRank ==4){
Intent i = new Intent(getActivity(),SettingsActivity.class);
getActivity().startActivity(i);
}
}
});
m_homeOfferLV.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
setListViewHeightBasedOnChildren(m_homeOfferLV);
}
//***************************************
// GOOGLE CONNECTION METHODS
//***********************************
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
profilePicPB.setVisibility(View.GONE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
}
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, listView.getLayoutParams().WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
Edit: Included the 3rd fragment's layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="0dp"
android:fillViewport="true"
android:gravity="top">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/customborder">
<ImageView
android:id="#+id/profile_pic"
android:layout_width="400px"
android:layout_height="400px"
android:layout_marginBottom="3dp"
android:background="#drawable/com_facebook_profile_picture_blank_square" />
<ProgressBar
android:id="#+id/profile_pic_progress_bar"
style="#android:style/Widget.ProgressBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
<TextView
android:id="#+id/user_name_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:textSize="15sp"
android:textStyle="bold" />
<ListView
android:id="#+id/me_tab_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:divider="#null"
android:dividerHeight="0dp" />
</LinearLayout>
Since your code is identical for every fragment look for the reason in the third fragment's layout.
First of all change root ScrollView parameters like this:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroll_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
I suppose original android:layout_height="0dp" isn't processed as you expect, so fragment is actually inflated and added but you just don't see it.
Related
I have silder layout.xml in rss fragment. I do not know how to call them in fragment. I need to put some rss feed one link and get the data. Let me know if you know anyone
EnchantedViewPager
<com.Tamillive.newspaper.EnchantedViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="210dp" />
Rss feed layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp">
<com.Tamillive.newspaper.EnchantedViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="210dp" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator_unselected_background"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="5dp"
android:layout_marginEnd="10dp"
app:ci_drawable="#drawable/selecteditem_dot"
app:ci_drawable_unselected="#drawable/nonselecteditem_dot"
app:ci_height="6dp"
app:ci_width="6dp"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#color/background_white"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list"
style="#style/listStyleNoPadding"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:focusable="false" />
</LinearLayout>
</LinearLayout>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<com.facebook.shimmer.ShimmerFrameLayout
android:id="#+id/shimmer_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:shimmer_duration="1000">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="#+id/lyt_shimmer_recipes_list_big"
layout="#layout/include_shimmer_recipes_list_big" />
</RelativeLayout>
</com.facebook.shimmer.ShimmerFrameLayout>
</RelativeLayout>
RssFragment
public class RssFragment extends Fragment {
// Added argument key for URL
private static final String ARG_URL = "url_string";
public static final int RECIPES_LIST_SMALL = 0;
public static final int RECIPES_LIST_BIG = 1;
public static final int RECIPES_GRID_2_COLUMN = 2;
public static final int RECIPES_GRID_3_COLUMN = 3;
private RSSFeed rssFeed = null;
private ArrayList<RSSItem> postsList;
private RssAdapter listAdapter;
private ViewModeUtils viewModeUtils;
private SwipeRefreshLayout swipeRefreshLayout;
SharedPref sharedPref;
private Activity mAct;
private RelativeLayout ll;
private String url;
private AdView mAdView;
private View rootView;
private ShimmerFrameLayout lyt_shimmer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_list_refresh, container, false);
return ll;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
lyt_shimmer = ll.findViewById(R.id.shimmer_view_container);
RecyclerView listView = ll.findViewById(R.id.list);
postsList = new ArrayList<>();
listAdapter = new RssAdapter(getContext(), postsList);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_PROGRESS);
listView.setAdapter(listAdapter);
listView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
swipeRefreshLayout = ll.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshItems();
initShimmerLayout();
}
private void initShimmerLayout() {
View lyt_shimmer_recipes_list_big = ll.findViewById(R.id.lyt_shimmer_recipes_list_big);
if (sharedPref.getRecipesViewType() == RECIPES_LIST_SMALL) {
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
} else if (sharedPref.getRecipesViewType() == RECIPES_LIST_BIG) {
lyt_shimmer_recipes_list_big.setVisibility(View.VISIBLE);
} else if (sharedPref.getRecipesViewType() == RECIPES_GRID_2_COLUMN) {
;
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
} else if (sharedPref.getRecipesViewType() == RECIPES_GRID_3_COLUMN) {
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
}
}
});
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAct = getActivity();
// get URL from arguments
url = RssFragment.this.getArguments().getString(ARG_URL);
refreshItems();
}
private class RssTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
// Pass the URL string as parameter to URL class
URL rssUrl = new URL(url);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
rssFeed = myRSSHandler.getFeed();
} catch (ParserConfigurationException | IOException | SAXException e) {
Log.printStackTrace(e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (rssFeed != null) {
if (rssFeed.getList().size() > 0) {
postsList.addAll(rssFeed.getList());
}
listAdapter.setHasMore(false);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_LIST);
swipeRefreshLayout.setRefreshing(false);
} else {
String message = null;
if (!url.startsWith("http"))
message = "Debug info: '" + url + "' is most likely not a valid RSS url. Make sure the url entered in your configuration starts with 'http' and verify if it's valid XML using validator.w3.org/feed";
Helper.noConnection(mAct, message);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_EMPTY);
swipeRefreshLayout.setRefreshing(false);
}
super.onPostExecute(result);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.rss_menu, menu);
viewModeUtils = new ViewModeUtils(getContext(), getClass());
viewModeUtils.inflateOptionsMenu(menu, inflater);
ThemeUtils.tintAllIcons(menu, mAct);
}
private void refreshItems() {
postsList.clear();
lyt_shimmer.setVisibility(View.GONE);
lyt_shimmer.stopShimmer();
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_PROGRESS);
new RssTask().execute(
);
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
lyt_shimmer.setVisibility(View.GONE);
lyt_shimmer.stopShimmer();
return;
}
swipeRefreshLayout.post(() -> {
swipeRefreshLayout.setRefreshing(show);
lyt_shimmer.setVisibility(View.VISIBLE);
lyt_shimmer.startShimmer();
});
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
lyt_shimmer.stopShimmer();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
viewModeUtils.handleSelection(item, new ViewModeUtils.ChangeListener() {
#Override
public void modeChanged() {
listAdapter.notifyDataSetChanged();
}
});
switch (item.getItemId()) {
case R.id.info:
//show information about the feed in general in a dialog
if (rssFeed != null) {
String FeedTitle = (rssFeed.getTitle());
String FeedDescription = (rssFeed.getDescription());
//String FeedPubdate = (myRssFeed.getPubdate()); most times not present
String FeedLink = (rssFeed.getLink());
AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
String titlevalue = getResources().getString(R.string.feed_title_value);
String descriptionvalue = getResources().getString(R.string.feed_description_value);
String linkvalue = getResources().getString(R.string.feed_link_value);
if (FeedLink.equals("")) {
builder.setMessage(titlevalue + ": \n" + FeedTitle +
"\n\n" + descriptionvalue + ": \n" + FeedDescription);
} else {
builder.setMessage(titlevalue + ": \n" + FeedTitle +
"\n\n" + descriptionvalue + ": \n" + FeedDescription +
"\n\n" + linkvalue + ": \n" + FeedLink);
}
builder.setNegativeButton(getResources().getString(R.string.ok), null)
.setCancelable(true);
builder.create();
builder.show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}}
// This is the factory to instantiate the RssFragment instance with the url string as arguments
public static RssFragment newInstance(String url) {
RssFragment newInstance = new RssFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_URL, url);
newInstance.setArguments(bundle);
return newInstance;
}
}
ScrollableTabsActivity
public class ScrollableTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_tabs);
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12847959/rss.xml"), "உலகம்");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12847980/rss.xml"), "சினிமா");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850122/rss.xml"), "வேலை வாய்ப்பு");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850077/rss.xml"), "டெக்னாலஜி");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850128/rss.xml"), "சமையலறை");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850092/rss.xml"), "விவசாயம்");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850103/rss.xml"), "கல்வி-வேலைவாய்ப்பு");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850110/rss.xml"), "விளையாட்டு");
viewPager.setAdapter(adapter);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
I need to put an rss feed link to something and get the data.
I have a gallery of images that shows the images in a recyclerviewusing glide and by clicking on each image in the recyclerview that image open in a view pager. every thing is ok in the beginning the recyclerview is fine, the images open in a viewpager and sliding in viewpager are all fine. but when i press back to close the viewpager and goback to recyclerview suddenly the allocated memory raises to about 400 MB!!!
there are 8 images that are about 490*420 pixel and 72 KB size.
MainGallery.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/recView_Gallery1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
>
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/btn_retry_Gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="تلاش مجدد"
android:textSize="16sp"
android:visibility="gone"
android:layout_gravity="center"
android:gravity="center"/>
</android.support.design.widget.CoordinatorLayout>
GalleryEnter.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="wrap_content"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/iv_photoGallety"
android:adjustViewBounds="true"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:layout_margin="2dp"
android:layout_width="match_parent"
android:background="#android:color/white"/>
</LinearLayout>
ImageDetail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.parsroyan.restaurant.imageDetailActivity">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
MainGalleryActivity.java
public class GalleryMain_Activity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
public static RecyclerView recListMenuTypes;
public static ImageAdapter mta;
ArrayList<ImageGallery> data = new ArrayList<>();
Button btn_retry;
TextView tv_message;
ImageView imv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_main_);
btn_retry = (Button) findViewById(R.id.btn_retry_Gallery);
recListMenuTypes = (RecyclerView) findViewById(R.id.recView_Gallery1)
;
recListMenuTypes.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new
GridLayoutManager(GalleryMain_Activity.this, 2);
recListMenuTypes.setLayoutManager(mLayoutManager);
//LinearLayoutManager llm = new
LinearLayoutManager(GalleryMain_Activity.this);
//llm.setOrientation(LinearLayoutManager.VERTICAL);
//recListMenuTypes.setLayoutManager(llm);
recListMenuTypes.setItemAnimator(new DefaultItemAnimator());
mta = new ImageAdapter(GalleryMain_Activity.this, data);
recListMenuTypes.setAdapter(mta);
Check_Connection_Retrive();
btn_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Check_Connection_Retrive();
}
});
}
private void alertView1(String message,boolean success) {
final TypedArray styledAttributes =
GalleryMain_Activity.this.getTheme().obtainStyledAttributes(new int[] {
android.R.attr.actionBarSize });
int Y = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
LayoutInflater inflater = getLayoutInflater();
View toastLayout = inflater.inflate(R.layout.custom_toast,
(ViewGroup)
findViewById(R.id.custom_toast_layout));
tv_message = (TextView)
toastLayout.findViewById(R.id.custom_toast_message);
tv_message.setText(message);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP | Gravity.START |
Gravity.FILL_HORIZONTAL,0,Y);
toast.setView(toastLayout);
imv_message = (ImageView)
toastLayout.findViewById(R.id.custom_toast_image);
if(!success){
toastLayout.setBackgroundColor(Color.parseColor("#cc0000"));
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_alert);
}
else {
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_info);
}
toastLayout.setAlpha(.8f);
toast.show();
}
public void Check_Connection_Retrive()
{
if(InternetConnection.checkConnection(getApplicationContext(),this))
{
btn_retry.setVisibility(View.GONE);
new FetchGallery().execute();
}
else
{
btn_retry.setVisibility(View.VISIBLE);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private class FetchGallery extends AsyncTask<String, String, String> {
TransparentProgressDialog pdLoading = new
TransparentProgressDialog
(GalleryMain_Activity.this,R.drawable.progress_circle);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {`enter code here`
super.onPreExecute();
//pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
//pdLoading.setProgress(10);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("My_URL");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "1";
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "2";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return "3";
}
} catch (IOException e) {
return "4";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
switch(result) {
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
try {
btn_retry.setVisibility(View.GONE);
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
//JSONObject json_data = jArray.getJSONObject(i);
ImageGallery image = new ImageGallery();
//image.name = json_data.getString("name");
image.title = jArray.get(i).toString();
image.url = "MY_URL" + image.title;
data.add(image);
}
// Setup and Handover data to recyclerview
mta.notifyDataSetChanged();
recListMenuTypes.addOnItemTouchListener(new
RecyclerViewTouchListener(getApplicationContext(), recListMenuTypes, new
RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(GalleryMain_Activity.this,
imageDetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
#Override
public void onLongClick(View view, int position){
}
}));
} catch (JSONException e) {
Toast.makeText(GalleryMain_Activity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
ImageAdapter.java
public class ImageAdapter extends
RecyclerView.Adapter<ImageAdapter.MenuViewHolder> {
private List<ImageGallery> imageGalleryList;
private Context context;
protected int lastPosition = -1;
public ImageAdapter(Context Context,List<ImageGallery> contactList)
{
this.imageGalleryList = contactList;
this.context = Context;
}
#Override
public int getItemCount() {
return imageGalleryList.size();
}
#Override
public void onBindViewHolder(ImageAdapter.MenuViewHolder menuViewHolder,
int i) {
final ImageGallery m = imageGalleryList.get(i);
Glide.with(context).load("MyURL"+m.title)
.thumbnail(.1f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.logoback)
.into(menuViewHolder.vImage);
setFadeAnimation(menuViewHolder,i);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public ImageAdapter.MenuViewHolder onCreateViewHolder(ViewGroup
viewGroup, int i) {
final View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_gallery_enter, viewGroup, false);
return new ImageAdapter.MenuViewHolder(itemView);
}
#Override
public void onViewDetachedFromWindow(ImageAdapter.MenuViewHolder holder)
{
((ImageAdapter.MenuViewHolder)holder).itemView.clearAnimation();
}
public class MenuViewHolder extends RecyclerView.ViewHolder{
protected ImageView vImage;
public MenuViewHolder(View v) {
super(v);
vImage = (ImageView) v.findViewById(R.id.iv_photoGallety);
}
}
private void setFadeAnimation(ImageAdapter.MenuViewHolder view, int
position) {
if (position > lastPosition) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 2.0f);
anim.setDuration(1000);
view.itemView.startAnimation(anim);
lastPosition = position;
}
}
}
ImageDetailActivity.java
public class imageDetailActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public ArrayList<ImageGallery> data = new ArrayList<>();
int pos;
Toolbar aboveToolbar;
/**
* 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_image_detail);
//aboveToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.detail_toolbar);
//setSupportActionBar(aboveToolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
setTitle(data.get(pos).getName());
// 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) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageGallery> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageGallery> 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).getUrl());
}
#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;
ImageView ImageView;
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 void onDestroy() {
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
this.ImageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.tiara3)
.into(this.ImageView);
return rootView;
}
}
}
error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:501)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:354)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
at android.content.res.Resources.loadDrawable(Resources.java:1970)
at android.content.res.Resources.getDrawable(Resources.java:660)
at com.bumptech.glide.request.GenericRequest.getPlaceholderDrawable(GenericRequest.java:416)
at com.bumptech.glide.request.GenericRequest.clear(GenericRequest.java:323)
at com.bumptech.glide.request.ThumbnailRequestCoordinator.clear(ThumbnailRequestCoordinator.java:106)
at com.bumptech.glide.manager.RequestTracker.clearRequests(RequestTracker.java:94)
at com.bumptech.glide.RequestManager.onDestroy(RequestManager.java:221)
at com.bumptech.glide.manager.ActivityFragmentLifecycle.onDestroy(ActivityFragmentLifecycle.java:64)
at com.bumptech.glide.manager.SupportRequestManagerFragment.onDestroy(SupportRequestManagerFragment.java:147)
at android.support.v4.app.Fragment.performDestroy(Fragment.java:2322)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1240)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1272)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:2186)
at android.support.v4.app.FragmentController.dispatchDestroy(FragmentController.java:271)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:388)
at android.support.v7.app.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
at android.app.Activity.performDestroy(Activity.java:5273)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1110)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3438)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3469)
at android.app.ActivityThread.access$1200(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
real device result:
enter image description here
smulator result:
enter image description here
Add below line in Application tag in Menifest file:
android:largeHeap="true"
I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.
Below is my code.
UserListFragment.java
public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment UsersListFragment.
*/
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
UsersListFragment fragment = new UsersListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
Log.i(TAG, "UsersListFragment onCreate");
users = new ArrayList<>();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh","userlistview");
preferenceEditor.commit();
FirebaseUtil uts = new FirebaseUtil(getContext());
uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
Log.i(TAG, Success);
setHasOptionsMenu(true);
String partnerKey = (String) response.get("key");
if (partnerKey != null) {
Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
String type = (String) typeCheck.get("type");
if (type.equals("chat")) {
String key1 = Global.getInstance().ownerId;
String key2 = partnerKey;
partnerKeyValue = partnerKey;
if (key2 != null) {
String currentPartner = Global.getInstance().partnerId;
if (currentPartner.length() > 0) {
if (currentPartner.equals(partnerKey)) {
} else {
Global.getInstance().unreadMessageUsers.add(partnerKey);
}
Global.getInstance().unreadMessageUsers.add(partnerKey);
} else {
}
}
}
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "UsersListFragment onResume");
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "UsersListFragment onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
FirebaseUtil util = new FirebaseUtil(getContext());
util.updateUserStatus(Global.getInstance().ownerId, "4");
Log.i(TAG, "UsersListFragment onDestroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(actionBar!=null) {
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setLogo(R.drawable.ic_logo);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
actionBar.setBackgroundDrawable(colorDrawable);
}
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
int vd = users.size();
view = inflater.inflate(R.layout.fragment_userslist, container, false);
listView = (ListView) view.findViewById(R.id.userdisplay);
adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
listView.setAdapter(adapter);
if (users.size()==0){
usersList();
}else {
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserData data = users.get(position);
Global.getInstance().someData = data.getId();
Global.getInstance().partnerId = data.getId();
int i = 0;
for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
String element = iter.next();
if (element.equals(data.getId().toString())) {
iter.remove();
}
}
data.setUnreadMessageCount(0);
users.remove(position);
users.add(position, data);
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(ChatFragment.DATA_RECEIVE, data.getName());
fragmentOne .setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.framecontainerMain, fragmentOne).commit();
}
});
// Inflate the layout for this fragment
return view;
}
public void usersList () {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
//get the data from userlist api
final String URL = "url";
String token = preferenceSettings.getString("authToken","");
final String userId = preferenceSettings.getString("userId","");
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id",userId);
params.put("auth_token",token);
progressBar.show();
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse:" +response);
String success = null;
try {
success = response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success == "true") {
JSONArray Array = null;
try {
//get the users
} else {
users.add(data);
}
}
Log.i(TAG, "arraylist");
adapter.notifyDataSetChanged();
onlineUsers();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
progressBar.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj;
} else {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.dismiss();
VolleyLog.e("Error: ", error.getMessage());
Log.i(TAG, "onErrorResponse:" +error.networkResponse);
}
});
ApplicationController.getInstance().addToRequestQueue(myRequest);
myRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void sortingArray(){
if (users.size()>0) {
synchronized (this) {
if (Global.getInstance().unreadMessageUsers.size() > 0) {
System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : Global.getInstance().unreadMessageUsers) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
System.out.println("\nSorted Map");
Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);
for (String key : unreadCount.keySet()) {
int count_unread = unreadCount.get(key);
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setUnreadMessageCount(count_unread);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}
synchronized (this) {
if (Global.getInstance().userStatus.size() > 0) {
try {
for (Object dict : Global.getInstance().userStatus) {
Map<String, Object> val = (Map<String, Object>) dict;
String key = val.keySet().iterator().next();
val.get(key).toString().trim();
int statusValue;
if (val.get(key).toString().equals("")) {
statusValue = 4;
} else {
statusValue = Integer.valueOf(val.get(key).toString());
}
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setOnlineStatus(statusValue);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}catch (ConcurrentModificationException e){
e.printStackTrace();
}
}
}
Log.i(TAG, users.get(0).getName());
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
return 1;
} else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
return -1;
} else {
return 0;
}
}
});
}
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
return -1;
} else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
return 1;
} else {
return 0;
}
}
});
Global.getInstance().userStatus.clear();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
public void TimerMethod() {
synchronized(this) {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
String checkView = preferenceSettings.getString("refresh", "");
if (checkView.equals("userlistview")) {
if (Global.getInstance().userStatus.size() > 0) {
sortingArray();
}
} else {
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh", "userlistview");
preferenceEditor.commit();
if (Global.getInstance().unreadMessageUsers.size() > 0){
sortingArray();
}
}
}
}
public void onlineUsers (){
String value;
for (UserData data : users) {
value = data.getId();
FirebaseUtil online = new FirebaseUtil(getContext());
online.onlineUsers(value, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
if (response == null) {
} else {
Global.getInstance().userStatus.add(response);
}
}
});
}
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.menu_userlist,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private void logoutUser(){
Intent I = new Intent(getActivity(), LoginActivity.class);
startActivity(I);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSearch :
return true;
case R.id.menuLogout :
logoutUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
myTimer.cancel();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String val);
}
}
menu_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="#string/search"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
<item android:id="#+id/menuLogout"
android:title="#string/logout"
android:icon="#drawable/ic_logout"
android:tint="#android:color/white"
app:showAsAction="always">
</item>
</menu>
CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<UserData> {
private Activity activity;
private List<UserData> messages;
public CustomAdapter(Activity context, int resource, List<UserData> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
packagename.CustomAdapter.ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
UserData data = getItem(position);
int viewType = getItemViewType(position);
layoutResource = R.layout.program_list;
if (convertView != null) {
holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(data.getName());
holder.id = data.geId();
holder.roleMsg.setText(data.getRole());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
private String id;
private TextView roleMsg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.textView1);
roleMsg = (TextView) v.findViewById(R.id.textView2);
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity implements UsersListFragment.OnFragmentInteractionListener {
private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
VideoFragment fragmentTwo ;
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
}
public void attemptLogin1() {
String test = "one";
String tested = "fail";
}
#Override
public void onFragmentInteraction(String uri) {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragmentOne = new ChatFragment();
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
}
I have written setHasOptionsMenu(true); in onCreate of UserFragment.java
The logout functionality works fine but the search isn't working.
I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(
Any help is appreciated.
Thanks in advance.
Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.
Remove this line and it will work
case R.id.menuSearch:
return true;
I know the same question has been asked so many times but I am not able to solve my issue.
I have created an Activity which has a ViewPager which should have 4 Pages.
I am using the same Fragment for all pages. The Fragment has a GridView which should be updated whenever I swipe to the other page.
Following are the classes & XML layouts I have used to create it.
Activity layout activity_discover.xml
<android.support.v4.view.ViewPager
android:id="#+id/activity_discover_view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/activity_discover_pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:textColor="#color/black"
android:textSize="#dimen/header_text" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
Activity DiscoverActivity.java
public class DiscoverActivity extends FragmentActivity implements OnClickListener, OnPageChangeListener
{
private final static String TAG = "DiscoverActivity";
private UtilDialog utilDialog;
MPagerAdapter adapterViewPager;
PagerTabStrip pagerTabStrip;
ViewPager viewPager;
public ArrayList<String> listCategory;
LMProgressDialog progressDialog;
private RelativeLayout relativeCountry;
private RelativeLayout relativeCity;
private TextView tvCountry;
private TextView tvCity;
private String selectedCategory;
private int selectedCityID = 0;
private int selectedCategoryID = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discover);
initParameters();
initView();
}
void initParameters()
{
progressDialog = new LMProgressDialog(this);
utilDialog = new UtilDialog(this);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
editor.commit();
selectedCategory = getResources().getString(R.string.adventure);
listCategory = new ArrayList<String>();
listCategory.add(getResources().getString(R.string.adventure));
listCategory.add(getResources().getString(R.string.night_life));
listCategory.add(getResources().getString(R.string.life_styles));
listCategory.add(getResources().getString(R.string.events));
}
void initView()
{
viewPager = (ViewPager) findViewById(R.id.activity_discover_view_pager);
viewPager.setOnPageChangeListener(this);
adapterViewPager = new MPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapterViewPager);
pagerTabStrip = (PagerTabStrip) findViewById(R.id.activity_discover_pager_tab_strip);
pagerTabStrip.setTabIndicatorColor(getResources().getColor(R.color.white));
}
#Override
protected void onDestroy()
{
super.onDestroy();
}
public class MPagerAdapter extends FragmentPagerAdapter
{
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
public MPagerAdapter(FragmentManager fm)
{
super(fm);
mFragmentManager = fm;
mFragmentTags = new HashMap<Integer, String>();
}
#Override
public int getCount()
{
return 4;
}
#Override
public Fragment getItem(int position)
{
Fragment fragment = Fragment.instantiate(DiscoverActivity.this,
FragmentMediaContent.class.getName(), null);
return fragment;
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment)
{
// record the fragment tag here.
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
}
return obj;
}
public Fragment getFragment(int position)
{
String tag = mFragmentTags.get(position);
if (tag == null)
return null;
return mFragmentManager.findFragmentByTag(tag);
}
#Override
public CharSequence getPageTitle(int position)
{
return listCategory.get(position).toString().toUpperCase();
}
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
#Override
public void onPageSelected(int position)
{
selectedCategoryID = position;
selectedCategory = listCategory.get(position);
try
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(Constants.CITY_ID, selectedCityID);
jsonObject.put(Constants.CATEGORY, selectedCategory);
makeJsonObjectRequest(Request.Method.POST, jsonObject, API.URL_LOAD_MEDIA);
} catch (JSONException e)
{
e.printStackTrace();
}
}
void prepareMediaList(JSONArray arrayMedia)
{
int noOfMedia = arrayMedia.length();
ArrayList<MediaType> listMedia = new ArrayList<MediaType>();
for (int i = 0; i < noOfMedia; i++)
{
try
{
JSONObject objectMedia = arrayMedia.getJSONObject(i);
int id = objectMedia.getInt(Constants.ID);
String category = objectMedia.getString(Constants.CATEGORY);
String mediaType = objectMedia.getString(Constants.MEDIA_TYPE);
int cityID = objectMedia.getInt(Constants.CITIES_ID);
String path = objectMedia.getString(Constants.PATH);
String thumbnailPath = objectMedia.getString(Constants.THUMBNAIL_PATH);
String description = objectMedia.getString(Constants.DESCRIPTION);
int userID = objectMedia.getInt(Constants.USERS_ID);
listMedia.add(new MediaType(id, mediaType, path, category, userID, cityID, 0, description, thumbnailPath));
} catch (JSONException e)
{
e.printStackTrace();
}
}
FragmentMediaContent fragment = (FragmentMediaContent) adapterViewPager.getFragment(selectedCategoryID);
Log.i(TAG, "fragment: " + fragment);
fragment.updateData(listMedia, selectedCategory);
}
}
Fragment class FragmentMediaContent.java:
public class FragmentMediaContent extends Fragment
{
private final static String TAG = "FragmentMediaContent";
public static final String FRAGMENT_POSITION = null;
private GridView gridView;
private UtilDialog utilDialog;
private SharedPreferences preferences;
private Editor editor;
private ArrayList<MediaType> listMedia;
MediaAdapter mediaAdapter;
private int cityID;
private String category;
LMProgressDialog progressDialog;
TextView tvTest;
public static FragmentMediaContent newInstance(int num)
{
FragmentMediaContent f = new FragmentMediaContent();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_media_content, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
initParameters();
initViews();
}
void initParameters()
{
getSize();
listMedia = new ArrayList<MediaType>();
utilDialog = new UtilDialog(getActivity());
progressDialog = new LMProgressDialog(getActivity());
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
editor = preferences.edit();
mediaAdapter = new MediaAdapter(getActivity(), listMedia);
}
void initViews()
{
tvTest = (TextView) getActivity().findViewById(R.id.fragment_media_content_tv_test);
tvTest.setText(category+" no of media");
tvTest.setVisibility(View.GONE);
gridView = (GridView) getActivity().findViewById(R.id.fragment_media_content_grid_view);
gridView.setAdapter(mediaAdapter);
}
/**
* MediaAdapter : ArrayAdapter class which prepares view for list of
* MediaType.
*
*/
class MediaAdapter extends ArrayAdapter<MediaType>
{
MediaAdapter(Context context, ArrayList<MediaType> list)
{
super(context, R.layout.cell_media_view, R.id.cell_media_view_tv_test, list);
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = super.getView(position, convertView, parent);
MediaViewHolder holder = (MediaViewHolder) row.getTag();
if (holder == null)
{
holder = new MediaViewHolder(row);
row.setTag(holder);
}
final MediaType mediaType = getMedia(position, this);
String thumbnailPath = mediaType.getThumbnailPath();
String path = mediaType.getPath();
String type = mediaType.getMediaType();
// imageLoader.get(type.equals(Constants.TYPE_IMAGE) ? path :
// thumbnailPath, ImageLoader.getImageListener(holder.ivMedia,
// R.drawable.logo, R.drawable.ic_launcher));
holder.ivType.setVisibility(type.equals(Constants.TYPE_IMAGE) ? View.GONE : View.VISIBLE);
holder.ivMedia.setLayoutParams(new FrameLayout.LayoutParams(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
Picasso.with(getActivity()).load(type.equals(Constants.TYPE_IMAGE) ? path : thumbnailPath).noFade().centerCrop().resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE).placeholder(R.drawable.loading)
.error(R.drawable.no_image).into(holder.ivMedia);
return row;
}
}
public void updateData(ArrayList<MediaType> listMedia, String category)
{
Log.i(TAG, "Updating data for: " + category);
Log.i(TAG, "No of media items: " + listMedia.size());
// this.listMedia.clear();
// this.listMedia.addAll(listMedia);
// mediaAdapter.notifyDataSetChanged();
mediaAdapter = new MediaAdapter(getActivity(), listMedia);
gridView.setAdapter(mediaAdapter);
tvTest.setText(category + ", No of Media : " + listMedia.size());
}
int THUMBNAIL_SIZE = 200;
/**
* #param position
* #return MediaType object from specified position
*/
private MediaType getMedia(int position, MediaAdapter mediaAdapter)
{
return (MediaType) mediaAdapter.getItem(position);
}
}
Fragment fragment_media_content.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/fragment_media_content_tv_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/white" />
<GridView
android:id="#+id/fragment_media_content_grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="5dip"
android:numColumns="3"
android:verticalSpacing="5dip" />
</LinearLayout>
On page swipe (or it could be any other event) I hit an API which gives me some data that I have to update in the corresponding Fragment.
Whenever I get the data from server I call the prepareMediaList method which calls the updateData method of Fragment. I can see in logs that there is data in list but that data is not shown in the Fragment's GridView (not even in TextView).
I am really not getting what is wrong in this.
Now it has become very frustrating, looks so simple but still couldn't find any solution.
Edit
I just tried with one Fragment only & it is working properly. So there is something which has to do with multiples.
Edit 2
I couldn't find the solution for this so I had to switch to alternate way. I removed the Fragments from ViewPager instead I added static views to it. In my case I added four GridViews to ViewPager. This was simple & bit complex but most important thing is, it is working the way I wanted.
But still I am looking for the answer.
After checking your code more in details i see you do not require to re-initliaze your MediaAdapter inside updateData method.
You simply require to update your updateData as
listMedia.clear();
this.listMedia.addAll(listMedia);
mediaAdapter.notifyDatasetChanged();
This will reload your data in gridview. Change i suggested will refresh the data in your arraylist which is being used for rendering gridview and then you notify your mediaAdapter to reload the list.
I am currently using normal horizontal navigation in my code such that when you click on the button, it will navigate to a new fragment horizontally. I want to make it such that instead of calling a new fragment it just expands /collapses upon clicking/clicking again. The code I have so far is :
Here is the activity:
public class ManageNewsCategoriesActivity extends AbsBaseDoubleButtonActivity {
private List<AdapterRow> mBreakingViews;
public HashSet<CategoryCheckableRow> mCategoriesMap = new HashSet<CategoryCheckableRow>();
private int mTitleId = R.string.title_manage;
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity.getApplicationContext(), ManageNewsCategoriesActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_news_categories);
overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.no_animation);
mActiveFragment = ManageNewsCategoriesFragment.newInstance(getSupportFragmentManager(), 0);
}
public void animateTitle(final int textViewId) {
animateTitle(textViewId, R.anim.slide_in_from_right);
}
public void animateTitle(final int textViewId, final int animationId) {
final TextView titleView = (TextView) findViewById(textViewId);
final Animation animation = AnimationUtils.loadAnimation(this, animationId);
titleView.startAnimation(animation);
}
public void setBreakingViews(final List<AdapterRow> categoryRows) {
mBreakingViews = categoryRows;
}
public List<CategoryCheckableRow> getBreakingViews() {
return removeHeaders(mBreakingViews);
}
public List<AdapterRow> getBreakingViewsCategoryRows() {
if (mBreakingViews == null) {
return null;
}
return AbsBaseManageNewsFragment.getAClone(mBreakingViews);
}
private List<CategoryCheckableRow> removeHeaders(final List<AdapterRow> mCategoryRows) {
final List<CategoryCheckableRow> items = new ArrayList<CategoryCheckableRow>();
if (mCategoryRows != null) {
for (final AdapterRow row : mCategoryRows) {
if (row instanceof CategoryCheckableRow) {
final CategoryCheckableRow item = (CategoryCheckableRow) row;
items.add(item);
}
}
}
return items;
}
public boolean isDoneButtonEnabled() {
return !mCategoriesMap.isEmpty();
}
public void updateCategoriesMap(final HashSet<CategoryCheckableRow> categoryRows) {
for (final CategoryCheckableRow row : categoryRows) {
if (!mCategoriesMap.add(row)) {
mCategoriesMap.remove(row);
}
}
}
#Override
protected int getTitleId() {
return mTitleId;
}
#Override
public void updateTitleId(final int titleId) {
mTitleId = titleId;
updateTitleId();
}
Here is the fragment:
public class ManageNewsCategoriesFragment extends Fragment implements OnClickListener,OnCheckedChangeListener {
public final static String TAG_MANAGE_NEWS_CATEGORIES_FRAGMENT = "ManageNewsCategoriesFragment";
public static final String TYPE = "Type";
public static final String BREAKINGVIEWS = "Breakingviews";
public static final String ANIMATION = "animation";
protected Button mPreferencesDoneButton;
public static ManageNewsCategoriesFragment newInstance(final FragmentManager manager, final int animation) {
final ManageNewsCategoriesFragment fragment = new ManageNewsCategoriesFragment();
final Bundle arguments = new Bundle();
arguments.putInt(ANIMATION, animation);
fragment.setArguments(arguments);
final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, R.id.manage_news_categories_container);
fragmentInfo.setFragmentTag(TAG_MANAGE_NEWS_CATEGORIES_FRAGMENT);
FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
return fragment;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_manage_news_categories, container, false);
final Bundle arguments = getArguments();
final int animation = arguments.getInt(ANIMATION, 0);
final ManageNewsCategoriesActivity activity = (ManageNewsCategoriesActivity) getActivity();
if (animation != 0) {
activity.animateTitle(R.id.actionbar_title, arguments.getInt(ANIMATION, 0));
}
return view;
}
protected void setupClickListeners() {
mPreferencesDoneButton = (Button) getActivity().findViewById(R.id.button_done);
Typeface face = Typeface.createFromAsset(mPreferencesDoneButton.getContext().getAssets(),
"fonts/proxima-nova-regular.ttf");
mPreferencesDoneButton.setTypeface(face);
mPreferencesDoneButton.setOnClickListener(this);
mPreferencesDoneButton.setEnabled(((ManageNewsCategoriesActivity) getActivity()).isDoneButtonEnabled());
}
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final TextView titleView = (TextView) getActivity().findViewById(R.id.actionbar_title);
titleView.setText(R.string.title_manage);
initManageNewsCategoriesFragment();
}
private void initManageNewsCategoriesFragment() {
setupClickListeners();
final Button breakingViewsButton = (Button) getView().findViewById(R.id.button_breakingviews);
breakingViewsButton.setOnClickListener(this);
}
#Override
public void onClick(final View view) {
final ManageNewsCategoriesActivity activity = (ManageNewsCategoriesActivity) getActivity();
switch (view.getId()) {
case R.id.button_breakingviews:
ManageBreakingViewsFragment.newInstance(getFragmentManager());
return;
case R.id.button_done:
syncNewsCategories(activity);
break;
default:
break;
}
activity.onBackPressed();
}
private void syncNewsCategories(final ManageNewsCategoriesActivity activity) {
final List<CategoryCheckableRow> breakingViews = activity.getBreakingViews();
if ( ArrayUtils.isNotEmpty(breakingViews)) {
RestService.start(activity, new UserCategoriesSyncOperation(NewsContentProvider.USER_CATEGORIES_URI, breakingViews));
}
}
}
Here is the corresponding xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button_breakingviews"
android:layout_width="match_parent"
android:layout_height="#dimen/manage_news_btn_ht"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:background="#drawable/manage_market_category_btnbg"
android:gravity="left|center_vertical"
android:paddingLeft="#dimen/frequent_padding_left"
android:text="#string/button_breakingviews"
android:textColor="#cccccc"
android:textSize="#dimen/title" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingRight="17.5dp"
android:paddingTop="0dp"
android:src="#drawable/arrow_chevron_selector" />
</RelativeLayout>
</LinearLayout>
</FrameLayout>
Any clue how to go about the same? Please explain programmatically and with respect to my code to avoid confusion.
Thanks!
I think what you want is a custom expandable list view. Here is a very good tutorial on it: ExpandableListView