Update SeekBar in Fragment with value from SharedPreferences - android

I have an app with action bar. It has a "Main" fragment and a "Preferences" fragment.
final Main main = new Main();
final Preferences preferences = new Preferences();
drawer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Fragment fragment= null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
case 0:
fragment = main;
break;
case 1:
fragment = preferences;
break;
}
fragmentManager.beginTransaction()
.replace(R.id.fragment1, fragment)
.commit();
drawerLayout.closeDrawers();
}
});
The "Preferences" fragment has a seekBar that is updated with a value from SharedPreferences. This is the relevant code that makes this within the "Preferences" fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
container.removeAllViews();
View view = inflater.inflate(R.layout.preferences, container, false);
fontSizeBar = (SeekBar) view.findViewById(R.id.fontSizeBar);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Preferences.this.getActivity().getBaseContext());
final int fontSize = preferences.getInt("fontSize", 10);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fontSizeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Log.v("Progress changed", "Font size: " + progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.v("Start touching", "Font size: " + seekBar.getProgress());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
Log.v("Stop touching", "Font size: " + seekBar.getProgress());
}
});
fontSizeBar.setMax(10);
fontSizeBar.setProgress(fontSize);
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.preferences, container, false);
}
The method onProgressChanged() is called, because I can see the output "Progress changed", "Font size: 10" in LogCat, but the SeekBar is not visually updated. Additionally,the SeekBar does not responds to the methods onStartTrackingTouch() and onStopTrackingTouch().
I will appreciate any information that could shed some light about the problem.

You're doing everything right, inflating the views and setting up the logic but at the end you do this:
return inflater.inflate(R.layout.preferences, container, false);
which will return a newly inflated layout(so you drop everything you previously done). Instead you need to return the view which you previously inflated:
return view;

Related

Android Spinner onItemSelected not being called inside Fragment

I have an activity which calls several fragments. In one of those fragments I am trying to create a dialog spinner programmatically and add it to the menu option (in toolbar). I manage to make it work (atleast the view is showing), but the onItemSelected it is not getting called.
My code:
public class NewsFeed extends Fragment {
private static final String TAG = "tag";
private String tag;
private ArrayAdapter<New> newsadapter;
private ArrayAdapter<Tag> tagsadapter;
private Spinner spinner;
public NewsFeed() {
setHasOptionsMenu(true);
}
public static NewsFeed newInstance(String tag) {
NewsFeed fragment = new NewsFeed();
Bundle args = new Bundle();
args.putString(TAG, tag);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
tag = getArguments().getString(TAG);
}
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle(tag);
NavigationView activitynav = (NavigationView) getActivity().findViewById(R.id.nav_view);
BottomNavigationView activitybuttomnav = (BottomNavigationView) getActivity().findViewById(R.id.navigation);
activitynav.setCheckedItem(R.id.nav_news);
activitybuttomnav.getMenu().getItem(1).setChecked(true);
View v = inflater.inflate(R.layout.fragment_news_feed, container, false);
//Spinner related code
tagsadapter = new TagsAdapter(getActivity(), android.R.layout.simple_spinner_item, (ArrayList<Tag>) ApplicationData.tags);
spinner = new Spinner(getActivity(), Spinner.MODE_DIALOG);
tagsadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setPrompt("Filtrar por categoria:");
spinner.setAdapter(tagsadapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
newsadapter = new NewsAdapter(getActivity().getApplicationContext(), 0, (ArrayList<New>) ApplicationData.news);
ListView listview = (ListView) v.findViewById(R.id.listview);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
NewsDisplay nd = NewsDisplay.newInstance(tag, ApplicationData.news.get(position).getNewsUrl());
ft.addToBackStack(null);
ft.replace(R.id.fragmentcontent, nd).commit();
}
});
listview.setAdapter(newsadapter);
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.filter_category) {
//For showing the spinner
spinner.performClick();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Already tried:
To make NewsFeed implementing OnItemSelectedListener.
To create the OnItemSelectedListener object inside SetOnItemSelectedListener.
Could you give me some help? It might have to do with this being a fragment and the toolbar is in the activity.
Spinner that was created dynamically (private val popupSpinner: Spinner by lazy { Spinner(this, Spinner.MODE_DIALOG) }), needs to have an assigned parent view. If it does not have it, the OnItemSelected is never called for some reason.
I wrote this hack to alleviate the problem. Added to parent view and hid it. Be sure not to run this in onResume() method and similar ones.
findViewById<ViewGroup>(android.R.id.content).addView(popupSpinner)
popupSpinner.visibility = View.INVISIBLE
PS. Some people might think that this question does not have an answer. But in the comments the author himself found a solution.

How not to make refresh pages in ViewPager

Issue
I'm using a ViewPager with fragments.
Every fragment has a button in its layout which, when clicked, should run a piece of code and then disappear.
If I click a button, it runs the code and disappears as programmed.
But if I swap away from that fragment of 2 tabs, and then I get back to it, it looks like the ViewPager killed the cache for that fragment and restored it with its default layout: so the button appears again.
How can I always keep saved the status of each fragment? I don't want the ViewPager to keep saved just the two fragments asides the one I'm looking at.
Images
Adapter
Here's my adapter:
public class MineAdapter extends PagerAdapter {
private Context mContext;
private LayoutInflater mLayoutInflater;
public MineAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
//Fill Data directly from Repository
return CenterRepository.getSingletonInstance().getListOfLavels().size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((FrameLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
System.out.println("Code executed");
final View itemView = mLayoutInflater.inflate(R.layout.carousal_page, container,
false);
switch (position) {
case 0:
itemView.setBackgroundResource(R.color.iron);
break;
case 1:
itemView.setBackgroundResource(R.color.coal);
break;
case 2:
itemView.setBackgroundResource(R.color.gold);
break;
}
//Mine Name
((TextView) itemView.findViewById(R.id.mineName)).setText(
CenterRepository.getSingletonInstance().getListOfLavels().get(position).getmName());
//Mine Cost
((TextView) itemView.findViewById(R.id.mineCost)).setText("" +
CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost());
//Mine Cost
((TextView) itemView.findViewById(R.id.mineDropRate)).setText("" +
CenterRepository.getSingletonInstance().getListOfLavels().get(position).getDropRate());
//Mineral Name
((TextView) itemView.findViewById(R.id.mineMineral)).setText(
CenterRepository.getSingletonInstance().getListOfLavels().get(position).getMineral().getName());
//Mineral Drop Rate
((TextView) itemView.findViewById(R.id.mineDropRate)).setText("" +
CenterRepository.getSingletonInstance().getListOfLavels().get(position).getMineral().getValue());
// Unlock Button
itemView.findViewById(R.id.unlockButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CenterRepository.getSingletonInstance().getCurrentUser().getGold() >=
CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost()) {
//If User has more gold than cost to unlock remove lock image and buy it
CenterRepository.getSingletonInstance().getCurrentUser().setGold(
CenterRepository.getSingletonInstance().getCurrentUser().getGold()
- CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost()); // Update user's gold
itemView.findViewById(R.id.unlockButton).setVisibility(View.GONE); // Remove lock button
Toast.makeText(mContext,
"Reduced " + CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost() +
"\n Updated Gold " + CenterRepository.getSingletonInstance()
.getCurrentUser().getGold(), Toast.LENGTH_LONG).show();
} else {
// Not enough money
Toast.makeText(mContext, "Not enough money to purchase You need " +
(CenterRepository.getSingletonInstance().getListOfLavels().get(position).getUnlockCost()
- CenterRepository.getSingletonInstance().getCurrentUser().getGold()) + "More", Toast.LENGTH_SHORT).show();
}
}
});
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((FrameLayout) object);
}
}
public void setOffscreenPageLimit(int limit)
is what you need in for ViewPager view.
Android developer link for ViewPager
Save the state of the button's visibility in onSaveInstanceState and handle it accordingly in onViewCreated.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnTest = (Button) view.findViewById(R.id.btnTest);
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnTest.setVisibility(View.GONE);
}
});
if(savedInstanceState != null){
btnTest.setVisibility(savedInstanceState.getInt("button_visibility",View.VISIBLE));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("button_visibility",btnTest.getVisibility());
super.onSaveInstanceState(outState);
}

Show animations on every viewpager change

I want to show animations on every content of layout inflater. Below is the code that I am using but the problem is animations shows only on first page of view pager.
What I have understood so far is that animations on all pages content gets loaded on position 0 but I may be wrong.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = null;
if (position == 0) {
Home.rel_footer.setVisibility(View.VISIBLE);
v = inflater.inflate(R.layout.reward_points_circles, container,
false);
YoYo.with(Techniques.ZoomIn).duration(5000)
.playOn(v.findViewById(R.id.circle_1));
YoYo.with(Techniques.ZoomIn).duration(5000)
.playOn(v.findViewById(R.id.circle_2));
YoYo.with(Techniques.ZoomIn).duration(5000)
.playOn(v.findViewById(R.id.circle_3));
} else if (position == 1) {
Home.rel_footer.setVisibility(View.GONE);
v = inflater.inflate(R.layout.qrcode_scanner_promotion, container,
false);
YoYo.with(Techniques.Landing).duration(5000)
.playOn(v.findViewById(R.id.imgView_iphone));
YoYo.with(Techniques.Landing).duration(5000)
.playOn(v.findViewById(R.id.imgView_ipad));
} else if (position == 2) {
Home.rel_footer.setVisibility(View.GONE);
v = inflater.inflate(R.layout.deals_promotion, container, false);
YoYo.with(Techniques.ZoomIn).duration(5000)
.playOn(v.findViewById(R.id.imgView_iphone_left));
YoYo.with(Techniques.ZoomIn).duration(5000)
.playOn(v.findViewById(R.id.imageView_iphone_front));
YoYo.with(Techniques.ZoomIn).duration(5000)
.playOn(v.findViewById(R.id.imgView_iphone_right));
}
return v;
}
In my opinion you should not apply animations in onCreateView if you want to see your animation on each page change. You should instead use OnPageChangeListener interface and apply your animation there once user has changed a pager (switching to another page).
A simple code snippet to get you started.
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageSelected (int position){
// Apply animations here w.r.t the position
}
... Other overridden methods ...
});
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 1:
//load ur animations here
break;
default:
break;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});

setOnItemClickListener event doesn't work in Fragment

I am trying to get onItemClick on ListItems to work from a fragment. Here is my code:
public class MyBudgetPageMenuFragment extends Fragment {
private Context context;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.my_budget_listview,
container, false);
ListView listView = (ListView) myFragmentView
.findViewById(android.R.id.list);
context = this.getActivity().getApplicationContext();
String[] values = new String[4];
ListAdapter adapter = new ListAdapter(context, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener( new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
selectItem(position);
}
});
return myFragmentView;
}
private void selectItem(int position) {
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment;
switch (position) {
case 0:
fragment = new MyBudgetPageFragments();
fragmentManager.beginTransaction()
.replace(R.id.listFragment, fragment).commit();
break;
default:
String message1 = Integer.toString(position);
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setMessage("Position: " + message1);
alertDialog.show();
break;
}
}
}
But every time when I select an item, it isn't doing anything or throwing any exceptions. It seems that the event doesn't get registered. I debuged the code and it doesn't enter my event.
Can someoane tell me what I'm doing wrong?
Note that the ListView blocks clicks of an item that contains at least one focusable
descendant but it doesn’t make the content focus-reachable calling
setItemsCanFocus(true). One workaround is by disabling focusability of descendants, using
android:descendantFocusability="blocksDescendants"
in the layout defining your list item. (First learned of this myself from http://cyrilmottier.com/2011/11/23/listview-tips-tricks-4-add-several-clickable-areas/) Does your layout contain buttons? If so, you'd fall into this case.
Just go the simple way.
In your Adapter class, between getView method, initialize View v = convertView; then
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "test "+ list.get(position).getS_name(), Toast.LENGTH_SHORT).show();
}
});

how to update data on fragment when user change the page by using ViewPager from FragmentActivity?

I am looking for great solution for update the fragment content when user change the page with the help of ViewPager that is implemented on FragmentActivity.I have implemented FragementActivity as follows:
InformationActivity extends FragmentACtivity
List<Fragment> fragments = new Vector<Fragment>();
private void initialisePaging() {
for(int i=0;i<getCount;i++){
fragments.add(Fragment.instantiate(this, DetailInfoFragment.class.getName()));
}
this.mPagerAdapter = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) super.findViewById(R.id.viewPager);
pager.setAdapter(this.mPagerAdapter);
pager.setCurrentItem(itemNumber);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v("onPageSelected", "arg0 "+arg0);
MyAdapter getVal = new MyAdapter(InformationActivity.this);
Log.v("InformationActivity ", "getTitle : == > "+getVal.titles[arg0]);
Log.v("InformationActivity ", "getSubTitle : == > "+getVal.subTitles[arg0]);
getSharedPreferences("Values", 0).edit().putString("Title", getVal.titles[arg0]).commit();
getSharedPreferences("Values", 0).edit().putString("SubTitle", getVal.subTitles[arg0]).commit();
getSharedPreferences("Values", 0).edit().putInt("Image", getVal.images[arg0]).commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
I have used shared preference for share the data in between Activity and Fragments.
I have implemented DetailInfoFragment extends Fragments as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View f1Vew = inflater.inflate(R.layout.details, container, false);
imageIcon = ((ImageView)f1Vew.findViewById(R.id.imagLrg));
titleTxt = ((TextView)f1Vew.findViewById(R.id.titleText));
subTxt = ((TextView)f1Vew.findViewById(R.id.subTitleText));
String titleMain = getActivity().getSharedPreferences("Values", 0).getString("Title", "");
String subMain = getActivity().getSharedPreferences("Values", 0).getString("SubTitle", "");
Log.v("DetailInfoFragment : ", "tilte : "+titleMain);
Log.v("DetailInfoFragment : ", "subMain : "+subMain);
titleTxt.setText(""+titleMain);
subTxt.setText(""+subMain);
imageIcon.setImageResource(getActivity().getSharedPreferences("Values", 0).getInt("Image", 0));
return f1Vew;
}
From the above implementation i am getting same title and sub title from InformationActivity to DetailsFragment when user swipe on page with the help of view pager.But my issue here is The Fragment content is not updating(titleTxt,subTxt,imageIcon) with title,sub title,image icon.please how can i update fragment content in my case

Categories

Resources