How to refresh fragment on spinner on item selected - android

I am setting a language in spinner on item selected. The change is not reflected on the next line. So, I want to refresh my fragment.
public class TodayChapter extends Fragment {
String chapter_verse = "";
TextView textView;
ListView todayChapterListView;
ArrayAdapter<String> adapter;
DailyQuranMethods dailyQuranMethods = new DailyQuranMethods();
private final String[] translateLanguage={"Translate To","English","Urdu","Hindi"};
public TodayChapter() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_today_chapter, container, false);
todayChapterListView = (ListView)view.findViewById(R.id.today_chapter_list_view);
Spinner spinner = (Spinner)view.findViewById(R.id.selectLanguage);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_spinner_item, translateLanguage );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position)
{
case 0:
dailyQuranMethods.setTranslationLanguage(getActivity().getBaseContext(), "english");
break;
case 1:
dailyQuranMethods.setTranslationLanguage(getActivity().getBaseContext(),"english");
break;
case 2:
dailyQuranMethods.setTranslationLanguage(getActivity().getBaseContext(),"urdu");
break;
default:
dailyQuranMethods.setTranslationLanguage(getActivity().getBaseContext(),"hindi");
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String[] chapter = dailyQuranMethods.getChapter(dailyQuranMethods.getChapterNoToday(getActivity().getBaseContext()), dailyQuranMethods.getTranslationLanguage(getActivity().getBaseContext()), getActivity());
String chapterName = getActivity().getResources().getStringArray(R.array.chapters_name_arabic)[dailyQuranMethods.getChapterNoToday(getActivity().getBaseContext()) - 1 ];
TextView textView = (TextView)view.findViewById(R.id.chapterName);
textView.setText(chapterName);
adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,chapter);
todayChapterListView.setAdapter(adapter);
return view;
}
}
I can also call a method on each on item selected change. But, I want it by refreshing the fragment. In each switch case, I want to refresh the fragment. Please help me to solve this.
Edit 1:
There are three fragments, which are attached with the main activity:
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Today's Verse"),
TodayVerse.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Today's Chapter"),
TodayChapter.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Complete Qur'an"),
completeQuran.class, null);

You can simply detach and attach fragment as below
Fragment currentFragment = getFragmentManager().findFragmentByTag("tab2");
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
This will refresh the view and locale will change

Related

BottomNavigation View back button on pressed change state

So let me try to explain this: I have a Bottom navigation view with three buttons, each one when pressed will load a fragment. However, when pressing the back button, i have programmed the back stack to go back to the fragment it was previously. However, the colour of the navigation button does not change after the back button is changed. I know this has something to do with the state checked thing but i do not know how to implement it on my codes. Here are the codes
This is the menu page, it sets the bottomnavigation view only in which the main_frame is where the fragments are going to be:
public class menuPage extends AppCompatActivity {
BottomNavigationView mainNav;
FrameLayout mainFrame;
private MoviesFragment moviesFragment;
private HomeFragment homeFragment;
private ProfileFragment profileFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_page);
mainFrame= (FrameLayout) findViewById(R.id.main_frame);
mainNav = (BottomNavigationView) findViewById(R.id.main_nav);
moviesFragment= new MoviesFragment ();
homeFragment = new HomeFragment();
profileFragment = new ProfileFragment ();
removeFragment(homeFragment);
mainNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_movies :
setFragment(moviesFragment);
return true;
case R.id.nav_home :
setFragment(homeFragment);
return true;
case R.id.nav_profile:
setFragment(profileFragment);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.addToBackStack("detail");
fragmentTransaction.commit();
}
private void removeFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_frame, fragment);
fragmentTransaction.disallowAddToBackStack();
fragmentTransaction.commit();
}
}
Here is the codes for the Home Fragment, Movies Fragment and Profile Fragment respectively. You can ignore the codes written inside cos i know it correctly goes to another activity when launched and that has nothing to do with this issue
Home Fragment
public class HomeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_agenda, container, false);
return view;
}
}
Movies Fragment
public class MoviesFragment extends Fragment {
ListView listofmovies;
ArrayList<String> genres;
ArrayAdapter<String> listview;
NowShowing nowShowing;
ComingSoon comingsoon;
#Override//inflate this
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_movies, container, false);
listofmovies = (ListView) view.findViewById(R.id.movielist);
genres = new ArrayList<String>();
listview = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, genres);
listofmovies.setAdapter(listview);
//The types of options
genres.add("Now Showing");
genres.add("Coming Soon");
genres.add("July");
genres.add("June");
nowShowing = new NowShowing();
comingsoon = new ComingSoon();
listofmovies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent nextPage = new Intent(view.getContext(), NowShowing.class);
startActivityForResult(nextPage,0);
}
if (position == 1){
Intent nextPage = new Intent(view.getContext(),ComingSoon.class);
startActivityForResult(nextPage,1);
}
}
});
return view;
}
}
Profile Fragment
public class ProfileFragment extends Fragment {
ListView management;
ArrayList<String> mis;
ArrayAdapter<String> Adapter;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile,container, false );
management= (ListView) view.findViewById(R.id.management);
mis= new ArrayList<String>();
Adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, mis);
management.setAdapter(Adapter);
//add management settings
mis.add("Settings");
mis.add("Favourites");
mis.add("Log Out");
userprofilefragment userprofilefragment = new userprofilefragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.profilelayout, userprofilefragment, userprofilefragment.getTag())
.commit();
return view;
}
Help is much appreciated. The context is that I'm just making a simple movie app for school assignment and i am still kinda beginner at Java..
Thanks

Fragment List view replace

When i replace fragment Listview place fragment Listview
I had trouble this in photo but i can't fix it .
i need to fix it,plz.
UI_screenshot
Code
#Override
public void onActivityCreated(Bundle savedInstanceState) {
final String[] titel = {"asdasd", "asda", "bdfg", "asdqweqwe"};
int idimg = R.mipmap.icon_main_list;
MyArrayAdapter adapter = new MyArrayAdapter(getActivity(), titel, idimg);
setListAdapter(adapter);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
switch (position) {
case 0:
Anmalz anmalz=new Anmalz();
Main_List_Fragment main_list_fragment=new Main_List_Fragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment, anmalz);
fragmentTransaction.remove(main_list_fragment).commit();
break;
Change your onCreateView() to -
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment_list, container, false);
}
Also, in onListItemClick(), you should not remove/replace the same fragment again and again. You should just refresh the list adapter.

Fragment Changes when Screen is rotated

I have two fragments, FragmentCity and Fragmentnumber1. When screen orientation changes on fragmentnumber1, it goes back to FragmentCity. Does anyone know how to solve this? I appreciate it if you could show me how to solve this issue
FragmentCity
public class FragmentCity extends Fragment {
final String[] items = new String[]{"FC1", "FC2", "FC3", "FC4","FC5"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.haz, container, false);
ListView list = (ListView) view.findViewById(R.id.fir);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Fragment myFragment = null;
switch (arg2) {
case 0:
myFragment = new Fragmentnumber1();
break;
case 1:
myFragment = new Fragmentnumber2();
break;
case 2:
myFragment = new Fragmentnumber3();
break;
case 3:
myFragment = new Fragmentnumber4();
break;
case 4:
myFragment = new Fragmentnumber5();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().addToBackStack("frag")
.replace(R.id.container2, myFragment)
.commit();
}
});
return view;
}
}
Fragmentnumber1
public class Fragmentnumber1 extends Fragment {
final String[] items = new String[]{"num1", "num2", "num3"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.haz, container, false);
ListView list = (ListView) view.findViewById(R.id.fir);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Fragment myFragment = null;
switch (arg2){
case 0:
myFragment = new num1();
break;
case 1:
myFragment = new num2();
break;
case 2:
myFragment = new num3();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().addToBackStack(null)
.replace(R.id.container2, myFragment)
.commit();
}
});
return view;
}
}
You have not posted code of activity class but i am guessing that you have loaded FragmentCity fragment in onCreate of your activity
So when you change orientation it again call onCreate and load FragmentCity fragment so by putting proper condition you can manage it.
Try adding the following line to your containing activity (probably MainActivity) in the manifest
<activity android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"/>
This will allow the Activity to maintain it's state across orientation changes.

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 setCurrentPage in ViewPager according to user selection & how do I know which list item called the activity

I'm new to Android programming.
I have a list of items, when the user clicks on an item it takes them to a screen with that item details.
I want the user to have the ability to swipe right and left to view other items' details in the list, instead of going back to the list and choosing another item.
I read that I need to use ViewPager for the ability to swipe right and left, so I did that.
ViewPager works fine, but my problem when I click any item on the list I always get to the first page in the ViewPager.
I don't want that, what I want is if I click on item 4 on the list it takes me to page 4 in the view pager and still have the ability to swipe right and left to view the details of other items.
I know how to set the page in viewpager by using mPager.setCurrentItem(0)
But I don't know how to set it according to which item was selected from the list (i.e which item launched the activity).
Here is my code:
Main activity which contains the listview:
public class Main extends SherlockListActivity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView mylist = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_reda_1, R.id.list_content, getResources().getStringArray(R.array.items_list_array) );
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0,View arg1, int position, long arg3)
{
Intent n = null;
switch (position){
case 0:
n = new Intent(getApplicationContext(), ViewPagerClass.class);
break;
case 1:
n = new Intent(getApplicationContext(), ViewPagerClass.class);
break;
case 2:
n = new Intent(getApplicationContext(), ViewPagerClass.class);
break;
case 3:
n = new Intent(getApplicationContext(), ViewPagerClass.class);
break;
}
if(null!=n)
startActivity(n);
}
});
}
}
ViewPagerClass
public class ViewPagerClass extends SherlockFragmentActivity{
static final int NUM_ITEMS = 4;
MyAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.viewpager_layout);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.viewpager);
mPager.setAdapter(mAdapter);
//mPager.setCurrentItem(2);
final ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayUseLogoEnabled(false);
ab.setDisplayShowHomeEnabled(false);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0: return FirstPageFragment.newInstance();
case 1: return SecondPageFragment.newInstance();
case 2: return ThirdPageFragment.newInstance();
case 3: return FourthPageFragment.newInstance();
}
return null;
}
}
public static class FirstPageFragment extends Fragment {
public static FirstPageFragment newInstance() {
FirstPageFragment f = new FirstPageFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment1, container, false);
return V;
}
}
public static class SecondPageFragment extends Fragment {
public static SecondPageFragment newInstance() {
SecondPageFragment f = new SecondPageFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment2, container, false);
return V;
}
}
public static class ThirdPageFragment extends Fragment {
public static ThirdPageFragment newInstance() {
ThirdPageFragment f = new ThirdPageFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment3, container, false);
return V;
}
}
public static class FourthPageFragment extends Fragment {
public static ThirdPageFragment newInstance() {
ThirdPageFragment f = new ThirdPageFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment4, container, false);
return V;
}
}
Finally viewpager_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+android:id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
So in short What I want is:
If I click on item 3 in the list I go to screen with the details on item 3, and if I swipe to the right I get to item 4, and if I swipe to the left I get to item 2.
In the onItemClickListener() you need to add an extra to the intent so you can get it when that activity launches.
n.putExtra("POSITION_KEY", position);
In the ViewPagerClass onCreate() using the
int position = getIntent().getIntExtra("POSITION_KEY", 0);
mPager.setCurrentItem(position);
That should do what you are wanting to do.

Categories

Resources