fragment_gelocalized.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="@+id/progressBar"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_width="200dp"
style="?android:attr/progressBarStyleLarge"
android:layout_height="200dp"
android:indeterminateDrawable="@drawable/ef_circular_progress_bar"
android:indeterminate="true" />
</RelativeLayout>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/layoutHome"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:scrollbars="vertical"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
MainActivity:
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabsHome(CalmettaRG, CalmettaBD);
}
// Tabs inizio
public void tabsHome (Typeface CalmettaRG, Typeface CalmettaBD){
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.tab_container);
setupViewPager(mViewPager);
tabLayout.setupWithViewPager(mViewPager);
String[] listTab = {
"0:Vicino a te:active",
"1:Consigliati:0"
};
for (String string: listTab) {
String[] parts = string.split(":");
Integer id = Integer.valueOf(parts[0]);
String name = parts[1];
String active = parts[2];
TextView textView = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_title,null);
tabLayout.getTabAt(id).setCustomView(textView);
TabLayout.Tab singleTab = tabLayout.getTabAt(id);
if(active.equals("active")) {
textView.setTypeface(CalmettaBD);
singleTab.select();
} else {
textView.setTypeface(CalmettaRG);
}
singleTab.setText(name);
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Typeface CalmettaBD = Typeface.createFromAsset(getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Bd.ttf");
Log.wtf("Tuttimenu MainActivity", "onTabSelected: ");
int tabCount = tabLayout.getTabCount();
for (int i = 0; i < tabCount; i++) {
tabLayout.getTabAt(i);
View tabView = tab != null ? tab.getCustomView() : null;
if (tabView instanceof TextView) {
((TextView) tabView).setTypeface(CalmettaBD);
}
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
Typeface CalmettaRG = Typeface.createFromAsset(getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Rg.ttf");
Log.wtf("Tuttimenu MainActivity", "onTabUnselected: ");
int tabCount = tabLayout.getTabCount();
for (int i = 0; i < tabCount; i++) {
tabLayout.getTabAt(i);
View tabView = tab != null ? tab.getCustomView() : null;
if (tabView instanceof TextView) {
((TextView) tabView).setTypeface(CalmettaRG);
}
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) { }
});
}
public void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new GeolocalizedFragment());
adapter.addFragment(new RecommendedFragment());
viewPager.setAdapter(adapter);
}
// Tabs fine
}
GeolocaliedFragment:
public class GeolocalizedFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
View view;
MainActivity mainActivity = new MainActivity();
String urlSite = mainActivity.getGlobalUrlSite();
Context context;
SwipeRefreshLayout mSwipeRefreshLayout;
RelativeLayout mRelativeLayout;
GetMenuHomeTaskWeb getMenuHome;
GPSTraker gpsTraker;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Menu> myDataset = new ArrayList<Menu>();
JSONArray menus;
JSONObject listMenus;
boolean flagDecoration = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
String greeting = (savedInstanceState != null) ? savedInstanceState.getString("greeting") : "null";
Log.i("Tuttimenu", " onCreate: " + greeting);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = getActivity();
Bundle update = getActivity().getIntent().getExtras();
if(update != null) {
Log.wtf("Tuttimenu HomeFragment", update.getString("EXTRA_UPDATE"));
}
view = inflater.inflate(R.layout.fragment_geolocalized, container, false);
Typeface CalmettaRG = Typeface.createFromAsset(getActivity().getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Rg.ttf");
Typeface CalmettaBD = Typeface.createFromAsset(getActivity().getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Bd.ttf");
/*TextView title = (TextView) view.findViewById(R.id.home_txt1);
title.setTypeface(CalmettaBD);
TextView subtitle = (TextView) view.findViewById(R.id.home_txt2);
subtitle.setTypeface(CalmettaRG);*/
// SwipeRefreshLayout
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
// Controllo se esistono menu nel db locale
DatabaseHelper database = new DatabaseHelper(context);
List<MenuLocal> menuLocalItems = database.listAllMenuLocal();
if(menuLocalItems.isEmpty()) {
// scarico e salvo i menu nel db locale
getMenu();
} else {
// utilizzo i menu del db locale
getMenuLocal();
}
// Inflate the layout for this fragment
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onRefresh() {
Log.wtf("Tuttimenu HomeFragment", "onRefresh called from SwipeRefreshLayout");
// scarico e salvo i menu nel db locale
getMenu();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
mSwipeRefreshLayout.setRefreshing(false);
}
}, 2000);
}
public void getMenu(){
mSwipeRefreshLayout.setVisibility(SwipeRefreshLayout.GONE);
mRelativeLayout = (RelativeLayout) view.findViewById(R.id.progress_bar);
mRelativeLayout.setVisibility(RelativeLayout.VISIBLE);
gpsTraker = new GPSTraker(context);
getMenuHome = new GetMenuHomeTaskWeb();
if(gpsTraker.canGetLocation()) {
double latitude = gpsTraker.getLatitude();
double longitude = gpsTraker.getLongitude();
String stringLat = Double.toString(latitude);
String stringLng = Double.toString(longitude);
Log.wtf("Tuttimenu GetMenuHome", "lat: " + stringLat + "lng: " + stringLng);
getMenuHome.setContext(context, "geolocalized", stringLat, stringLng);
} else {
gpsTraker.showSettingsAlert();
}
gpsTraker.stopUsingGPS();
try {
String result = getMenuHome.execute(urlSite).get();
// TODO da inserire una variale php che restituisce 0 result;
if(!result.isEmpty()) {
DatabaseHelper database = new DatabaseHelper(context);
database.setMenuLocal(new MenuLocal(result));
getHome(result);
mSwipeRefreshLayout.setVisibility(SwipeRefreshLayout.VISIBLE);
mRelativeLayout.setVisibility(RelativeLayout.GONE);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public void getMenuLocal(){
mSwipeRefreshLayout.setVisibility(SwipeRefreshLayout.GONE);
mRelativeLayout = (RelativeLayout) view.findViewById(R.id.progress_bar);
mRelativeLayout.setVisibility(RelativeLayout.VISIBLE);
DatabaseHelper database = new DatabaseHelper(context);
MenuLocal menuLocal = database.selectMenuLocal(1);
//Log.wtf("Tuttimenu GetMenuHomeLocal", menuLocal.getHome());
getHome(menuLocal.getHome());
mSwipeRefreshLayout.setVisibility(SwipeRefreshLayout.VISIBLE);
mRelativeLayout.setVisibility(RelativeLayout.GONE);
}
private void getHome(String result){
//Log.wtf("Tuttimenu GetMenuHome", "getHome: " + result);
try {
myDataset.clear();
listMenus = new JSONObject(result);
int x = listMenus.length();
for (int i = 0; i < x; i++){
menus = new JSONArray(listMenus.getString("home"));
int y = menus.length();
for (int a = 0; a < y; a++){
JSONObject jsonObject = (JSONObject) menus.get(a);
//Log.wtf("Tuttimenu GetMenuHome", jsonObject.getString("name"));
myDataset.add(new Menu(jsonObject.getInt("id"), jsonObject.getInt("id_type"),
jsonObject.getString("name"), jsonObject.getString("activity_name"),
jsonObject.getString("image"), jsonObject.getString("activity_image"),
jsonObject.getString("likes"), jsonObject.getString("views")));
}
}
mRecyclerView = (RecyclerView) view.findViewById(R.id.layoutHome);
mRecyclerView.setHasFixedSize(true);
/*mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerView.setItemViewCacheSize(20);*/
/*mRecyclerView.setDrawingCacheEnabled(true);
mRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);*/
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
if(!flagDecoration)
{
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
//mRecyclerView.setItemAnimator(new DefaultItemAnimator());
flagDecoration = true;
}
mAdapter = new MyAdapterHome((ArrayList<Menu>) myDataset, context);
mRecyclerView.setAdapter(mAdapter);
} catch (Throwable t) {
Log.wtf("Tuttimenu GetMenuHome", "Error mAdapter");
//Log.wtf("Tuttimenu GetMenuHome JSON", "Impossibile analizzare array JSON getHome: \"" + result + "\"");
//Toast.makeText(mcontext, "Impossibile analizzare array JSON getHome: \"" + result + "\"", Toast.LENGTH_LONG).show();
}
}
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int halfSpace;
public SpacesItemDecoration(int space) {
this.halfSpace = space / 2;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getPaddingLeft() != halfSpace) {
parent.setPadding(halfSpace, halfSpace, halfSpace, halfSpace);
parent.setClipToPadding(false);
}
outRect.top = halfSpace;
outRect.bottom = halfSpace;
outRect.left = halfSpace;
outRect.right = halfSpace;
}
}
}
MyAdapterHome:
public class MyAdapterHome extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Menu> mDataset;
private Context context;
MainActivity mainActivity = new MainActivity();
String urlSite = mainActivity.getGlobalUrlSite();
public MyAdapterHome(ArrayList<Menu> mDataset, Context context) {
this.context = context;
this.mDataset = mDataset;
}
@Override
public int getItemViewType(int position) {
// Just as an example, return 0 or 2 depending on position
// Note that unlike in ListView adapters, types don't have to be contiguous
Menu menu = mDataset.get(position);
return menu.getId_type();
}
ViewHolder vh;
ViewHolderADS vhads;
LayoutInflater mInflater;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mInflater = LayoutInflater.from ( parent.getContext () );
switch (viewType){
case 9:
View cardADS = ( View ) mInflater.inflate ( R.layout.card_ads, parent, false );
vhads = new ViewHolderADS(cardADS);
return vhads;
default:
View cardMenu = ( View ) mInflater.inflate ( R.layout.card_menu, parent, false );
vh = new ViewHolder(cardMenu);
return vh;
}
}
ViewHolder ViewHolder;
ViewHolderADS ViewHolderADS;
Resources resources;
Typeface CalmettaTrialLight, CalmettaRG, CalmettaBD;
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
getItemViewType(position);
Menu menu = mDataset.get(position);
CalmettaTrialLight = Typeface.createFromAsset(holder.itemView.getContext().getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Lt.ttf");
CalmettaRG = Typeface.createFromAsset(holder.itemView.getContext().getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Rg.ttf");
CalmettaBD = Typeface.createFromAsset(holder.itemView.getContext().getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Bd.ttf");
switch (menu.getId_type()){
case 1:
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "Menù", "ef_menu_shadow", "ic_menu_white", menu, resources);
break;
case 2:
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "Vini", "ef_wine_shadow", "ic_wine_white", menu, resources);
break;
case 3:
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "Birre", "ef_beers_shadow", "ic_beers_white", menu, resources);
break;
case 4:
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "Cocktails", "ef_cocktails_shadow", "ic_cocktails_white", menu, resources);
break;
case 5:
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "Dolci", "ef_dessert_shadow", "ic_dessert_white", menu, resources);
break;
case 6:
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "Asporto", "ef_takeaway_shadow", "ic_takeaway_white", menu, resources);
break;
case 7:
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "Delivery", "ef_delivery_shadow", "ic_delivery_white", menu, resources);
break;
case 8:
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "All You Can Eat", "ef_allyoucaneat_shadow", "ic_allyoucaneat_white", menu, resources);
break;
case 9:
ViewHolderADS = (ViewHolderADS)holder;
viewHolderADS(ViewHolderADS, menu);
//TODO da sistemare il codice per la visulizzazione delle promozioni "Banner"
break;
case 10:
//TODO inserite grafica del menu vetrina
ViewHolder = (ViewHolder)holder;
viewHolder(ViewHolder, menu);
setTemplateMenu(ViewHolder, "Vetrina", "ef_allyoucaneat_shadow", "ic_allyoucaneat_white", menu, resources);
break;
}
}
public void viewHolderADS(ViewHolderADS holder, Menu menu){
String replacedStringADS = urlSite.replace("/index.php", "/images");
String imagePathADS = replacedStringADS + "/menus/" + menu.getImagePath();
PicassoCache.getPicassoInstance(ViewHolderADS.imageMenu.getContext()).load(imagePathADS).into(ViewHolderADS.imageMenu);
resources = holder.itemView.getResources();
}
public void viewHolder(final ViewHolder holder, final Menu menu){
String replacedString = urlSite.replace("/index.php", "/images");
String imagePath = replacedString + "/menus/" + menu.getImagePath();
String imageActivityPath = replacedString + "/activity/logo/" + menu.getImageActivityPath();
PicassoCache.getPicassoInstance(ViewHolder.imageMenu.getContext()).load(imagePath).into(ViewHolder.imageMenu);
PicassoCache.getPicassoInstance(ViewHolder.imageMenu.getContext()).load(imageActivityPath).transform(new CircleTransform()).into(ViewHolder.imgCorners);
//Picasso.with(holder.imageView.getContext()).load(replacedString + mDataset.get(position)).into(holder.imageView);
Typeface CalmettaTrialLight = Typeface.createFromAsset(holder.itemView.getContext().getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Lt.ttf");
Typeface CalmettaRG = Typeface.createFromAsset(holder.itemView.getContext().getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Rg.ttf");
Typeface CalmettaBD = Typeface.createFromAsset(holder.itemView.getContext().getAssets(), "fonts/calmetta_trial/Calmetta_Trial_Bd.ttf");
ViewHolder.mTitle.setTypeface(CalmettaBD);
ViewHolder.mTitle.setText(menu.getNameActivity());
/*holder.mTitle.setSingleLine(true);
holder.mTitle.setEllipsize(TextUtils.TruncateAt.END);*/
ViewHolder.mSubTitle.setTypeface(CalmettaRG);
resources = holder.itemView.getResources();
holder.txtLikes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.wtf("Tuttimenu MyAdapterHome", "Click like");
Toast.makeText(view.getContext(), "Likes " + menu.getLikes(), Toast.LENGTH_LONG).show();
}
});
holder.imageMenu.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onClick(View view) {
Log.wtf("Tuttimenu MyAdapterHome", "Click Image");
Toast.makeText(view.getContext(), "Click Image!", Toast.LENGTH_LONG).show();
Intent menuActivity = new Intent(holder.itemView.getContext(), MenuActivity.class);
menuActivity.putExtra("EXTRA_NAME", menu.getName());
menuActivity.putExtra("EXTRA_IMAGE", menu.getImagePath());
menuActivity.putExtra("EXTRA_TYPE", "Menù classico");
//homeAdmin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//homeAdmin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,
holder.itemView.findViewById(R.id.imageMenu), "imgMenuTransition");
holder.itemView.getContext().startActivity(menuActivity, optionsCompat.toBundle());
//((Activity)mcontext).finish();
}
});
}
public void setTemplateMenu(ViewHolder holder, String name, String shadow, String icon, Menu menu, Resources resources){
holder.txtLikes.setText(menu.getLikes()+" Likes");
holder.txtViews.setText(menu.getViews()+" Views");
Drawable drawableAdsMenu = resources.getDrawable(resources.getIdentifier(shadow,"drawable","com.tuttimenu.app.tuttimenu"));
holder.imageTypeMenu.setImageResource(resources.getIdentifier(icon,"drawable","com.tuttimenu.app.tuttimenu"));
holder.bottomCardView.setBackgroundDrawable(drawableAdsMenu);
holder.txTypeMenu.setText(name);
}
@Override
public int getItemCount() {
return mDataset.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle, mSubTitle, txtLikes, txtViews, txTypeMenu;
public ImageView imageMenu, imgCorners, imageTypeMenu;
public RelativeLayout bottomCardView;
public ViewHolder(View itemView) {
super(itemView);
bottomCardView = (RelativeLayout) itemView.findViewById(R.id.bottomCardView);
imageMenu = (ImageView) itemView.findViewById(R.id.imageMenu);
imageTypeMenu = (ImageView) itemView.findViewById(R.id.imageTypeMenu);
imgCorners = (ImageView) itemView.findViewById(R.id.imgCorners);
mTitle = (TextView) itemView.findViewById(R.id.title);
txtLikes = (TextView) itemView.findViewById(R.id.txt_likes);
txtViews = (TextView) itemView.findViewById(R.id.txt_views);
mSubTitle = (TextView) itemView.findViewById(R.id.subtitle);
txTypeMenu = (TextView) itemView.findViewById(R.id.txt_typeMenu);
}
}
public class ViewHolderADS extends RecyclerView.ViewHolder {
public TextView mTitle, mSubTitle, txtLikes, txtViews, txTypeMenu;
public ImageView imageMenu, imgCorners, imageTypeMenu;
public RelativeLayout bottomCardView;
public ViewHolderADS(View itemView) {
super(itemView);
bottomCardView = (RelativeLayout) itemView.findViewById(R.id.bottomCardView);
imageMenu = (ImageView) itemView.findViewById(R.id.imageMenu);
imageTypeMenu = (ImageView) itemView.findViewById(R.id.imageTypeMenu);
imgCorners = (ImageView) itemView.findViewById(R.id.imgCorners);
mTitle = (TextView) itemView.findViewById(R.id.title);
txtLikes = (TextView) itemView.findViewById(R.id.txt_likes);
txtViews = (TextView) itemView.findViewById(R.id.txt_views);
mSubTitle = (TextView) itemView.findViewById(R.id.subtitle);
txTypeMenu = (TextView) itemView.findViewById(R.id.txt_typeMenu);
}
}
}
大家好,首先我想说我是JAVA编程的新手,我已经做了几次测试,我有这个代码(发布在下面),我想保存MainActivity滚动的位置所以当我从MenuActivity返回时,页面不会每次都刷新,我在哪里错了?