How to implement void OnFragmentInteractionListener? - java

When I launch my app I get following exception:
java.lang.RuntimeException: com.demo.mtin.mtin.MainActivity must implement OnFragmentInteractionListener
Can someone help me with this?
What code I need to add in MainActivity and where?
I have two blank fragments: PopularFragment and RatedFragment
MainActivity bellow:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
#Override
protected void onResume() {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String order = sharedPref.getString("order", "popular");
if (order.equals("popular")) {
getPopularMovies();
} else {
getTopRatedMovies();
}
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// uci i postaviti order -> popular
Log.d("NESTO", "NESTO-onCreate");
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

This is actually a pretty straight-forward error message, go for this:
public class MainActivity extends AppCompatActivity implements PopularFragment.OnFragmentInteractionListener, RatedFragment.OnFragmentInteractionListener { ...
#Override
public void onFragmentInteraction(Uri uri) {
}}
You must indicate that your activity implement the fragment's interface, then implement it (can be void though).
And have the following in your fragments :
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}

Related

How to start new Activity or refresh current Activity using viewpager

I have viewpager which is in fragment. I am looking to start a new activity or refresh the current activity using tabs on it
For now , I'm using this to open Fragment called "Sunday" and "Monday" But I would Like to add another tab and when user select this tab either refresh the current activity as same state when app is first opened or open new activity
Here is my code
public class MainActivity extends AppCompatActivity {
//RSS link
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new sectionB(), "SEC B");
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if (tab.getPosition() == 0) {
Intent i1 = new Intent(MainActivity.this, SagarActivity.class);
startActivity(i1);
//here you can do your refresh of start new activity
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
For Refresh
If you want to refresh whole activity you can call recreate() method of activity
in your case you are in a fragment so you need to get activity first so you can do like getActivity().recreate()
For start new activity
for open a new activity you can use startActivity()
i your case you can do Like this
Intent intent = new Intent(getActivity(),activity_you_want_to_start.class);
startActivity(intent);
Remember one more thing, always make user getActivity() not returning
null
Now in your case
you need to setup listener on your TabLayout like this then call above method
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs_dayscount);
tabLayout.setupWithViewPager(viewPager);
//setting listener on tabLAyout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if (tab.getPosition() == yourDesiredPositionNumber) {
//here you can do your refresh of start new activity
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
One Another Way is
You can also set Listener on ViewPager like this
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs_dayscount);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if(position==yourDesiredPositionNumber){
//here you can do your refresh of start new activity
}
super.onPageSelected(position);
}
});

Recyclerview in fragment not displaying alert dialog result right away

In my project I have a main activity with 3 fragments that are displayed via a ViewPager in a TabLayout on launch. In one of my fragments I have a RecyclerView and a FAB that, when clicked, launches an alert dialog that captures user input to be displayed in the RV in the fragment. Upon clicking ADD in the dialog, nothing appears in the RV but when I click the FAB and try again, it appears in the RV. So what I am saying, I have to input info in the FAB twice before it displays in my RV in my fragment. So I was wondering if someone could help me understand why this is happening. It seems like my RV in my frag is not being created right away, but all in all my app is not crashing so I have no log to post. I've research but to no avail. I am self taught so any help would be appreciated.
Fragment
public class SubjectsFrag extends DialogFragment implements CardAdapter.ClickListener,
SubjectsEditor.OnAddSubjectListener
{
private static final String TAG = SubjectsFrag.class.getSimpleName();
#NonNull
Context context;
private EditText titleView, teacherView;
private String sTitle, sTeacher;
public EmptyRecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
public CardAdapter cardAdapter;
public SubjectsModel model = null;
public ArrayList<SubjectsModel> subMod = new ArrayList<>();
DbHelper dbHelper;
#BindView(R.id.main_root)
ViewGroup root;
public SubjectsFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
FloatingActionButton fab = view.findViewById(R.id.fab_sub);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
titleView = view.findViewById(R.id.edit_subject);
teacherView = view.findViewById(R.id.edit_subject_teacher);
View emptyView = view.findViewById(R.id.empty_subject_view);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
cardAdapter = new CardAdapter(getContext(), subMod);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(cardAdapter);
return view;
}
#Override
public void itemClicked(View view, int position) {
}
#Override
public void OnAddSubjectSubmit(String title, String teacher)
{
SubjectsModel model = new SubjectsModel(sTitle, sTeacher);
model.setmTitle(title);
model.setmTeacher(teacher);
subMod.add(model);
cardAdapter.notifyDataSetChanged();
}
private void showDialog()
{
SubjectsEditor addSubjectDialog = new SubjectsEditor();
addSubjectDialog.setTargetFragment(this, 0);
addSubjectDialog.show(getFragmentManager(), null);
}
}
Dialog Fragment
public class SubjectsEditor extends DialogFragment
{
Context context;
private OnAddSubjectListener listener;
#BindView(R.id.main_root)
ViewGroup root;
public interface OnAddSubjectListener
{
void OnAddSubjectSubmit(String title, String teacher);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try{
listener = (OnAddSubjectListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement onAddSubjectListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.editor_subjects, container, false);
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
View view = LayoutInflater.from(getActivity()).inflate(R.layout.editor_subjects, root);
final EditText mTitle = view.findViewById(R.id.edit_subject);
final EditText mTeacher = view.findViewById(R.id.edit_subject_teacher);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(view)
.setTitle("Add Subject")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String sTitle = mTitle.getText().toString();
final String sTeacher = mTeacher.getText().toString();
listener.OnAddSubjectSubmit(sTitle, sTeacher);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Recycler Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder>
{
public ArrayList<SubjectsModel> subMod;
private OnItemClicked onClick;
static ClickListener clickListener;
Context context;
public CardAdapter(Context context, ArrayList<SubjectsModel> items)
{
this.context = context;
this.subMod = items;
}
#NonNull
#Override
public CardAdapter.CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
return new CardViewHolder(LayoutInflater.from(context).inflate(R.layout.subjects_item_list,
parent, false));
}
#Override
public void onBindViewHolder(final CardAdapter.CardViewHolder holder, final int position)
{
SubjectsModel currentSubject = subMod.get(position);
holder.titleView.setText(currentSubject.getmTitle());
holder.teacher.setText(currentSubject.getmTeacher());
}
public class CardViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
TextView titleView;
TextView teacher;
CardView cardView;
public CardViewHolder(View itemView)
{
super(itemView);
titleView = itemView.findViewById(R.id.subject_subject);
teacher = itemView.findViewById(R.id.subject_teacher_text);
cardView = itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (clickListener != null)
{
clickListener.itemClicked(view, getAdapterPosition());
Toast.makeText(context, R.string.hello_blank_fragment, Toast.LENGTH_SHORT).show();
}
}
}
#Override
public int getItemCount()
{
return subMod.size();
}
public interface OnItemClicked
{
void onItemClick(int position);
}
public void setOnClick(OnItemClicked onClick)
{
this.onClick = onClick;
}
public void setClickListener(ClickListener clicked)
{
CardAdapter.clickListener = clicked;
}
public interface ClickListener
{
public void itemClicked(View view, int position);
}
}
Fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_root">
<com.example.ashleighwilson.schoolscheduler.adapter.EmptyRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/empty_subject_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_subjects"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_sub"
style="#style/FAB" />
</RelativeLayout>
Main Activity
public class OverviewActivity extends AppCompatActivity
{
private NavigationView mNavigationView;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
CharSequence tabTitles[] = {"SUBJECTS", "TASKS", "CALENDER"};
int numOfTabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_nav);
Toolbar toolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
final ViewPager viewPager = findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, getSupportFragmentManager(), tabTitles, numOfTabs);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.syncState();
mNavigationView = findViewById(R.id.nav_view);
setupDrawerContent(mNavigationView);
/* FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}); */
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab)
{
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onBackPressed()
{
//DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_nav, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem)
{
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.nav_grades:
Intent gradesIntent = new Intent(this, GradesActivity.class);
startActivity(gradesIntent);
break;
case R.id.nav_notes:
Intent notesIntent = new Intent(this, NotesActivity.class);
startActivity(notesIntent);
break;
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawer.closeDrawer(GravityCompat.START);
}
}
Using notifyDataSetChanged() should do the trick. Check this answer
Giving it a once-over, nothing jumped out. You can use either the debugger or Log.d(String, String) calls to challenge your assumptions about what’s being called when. I’d take a closer look at when you call your adapter’s notifyDataSetChanged() and then at the getItemCount and bind or createViewHolder calls inside the adapter itself.

How to fix TabIndicator not moving with selected tab

I am using a tablayout to build my application but the tab indicator is not working when I slide within the tabs. Can anyone help me?I have tried adding the addOnTabSelectedListener but that did not work either.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
private DrawerLayout drawerLayout;
private String[] pageTitle = {"myPlanner", "News", "Parking"};
private String studyRooms = "http://library2.csumb.edu/mrbs/mobilenow.php";
public static String MYPREFERENCE = "myPref";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
setSupportActionBar(toolbar);
//create default navigation drawer toggle
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < 3; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
//set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//handling navigation view item event
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(this);
viewPager = (ViewPager)findViewById(R.id.view_pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
//setting Tab layout (number of Tabs = number of ViewPager pages)
//viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment frag = pagerAdapter.fragments[position];
if(frag != null && frag instanceof MapsFragment){
Toast.makeText(MainActivity.this, "On page Selected", Toast.LENGTH_LONG).show();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// viewPager.setOffscreenPageLimit(3);
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
}
class PagerAdapter extends FragmentPagerAdapter{
String tabTitles[] = new String[]{"myPlanner", "News", "Parking"};
public Fragment[] fragments = new Fragment[tabTitles.length];
Context context;
public PagerAdapter(FragmentManager fm, Context context){
super(fm);
this.context = context;
}
#Override
public int getCount(){
return tabTitles.length;
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
return new myPlanner();
case 1:
return new News();
case 2:
return new MapsFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position){
//Generate title based on item position
return tabTitles[position];
}
#Override
public Object instantiateItem(ViewGroup container, int position){
Fragment createdFragment = (Fragment)super.instantiateItem(container,position);
fragments[position] = createdFragment;
return createdFragment;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[],int[] grantResults){
if(requestCode == MapsFragment.MY_PERMISSIONS_REQUEST_LOCATION){
MapsFragment mapFragment = (MapsFragment) pagerAdapter.fragments[2];
if(mapFragment != null){
mapFragment.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
remove this:
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
And add:
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Also u should call tabLayout.setupWithViewPager(viewPager); after u set up the viewpager
viewPager = (ViewPager)findViewById(R.id.view_pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);

PreferenceFragment with AppCompatActivity Android

I'm trying to create a Preferencefragment or a PreferenceActivity using the tabs. Actually i can't do it and my code is simply:
The MainActivity
public class MainActivity extends AppCompatActivity {
private ViewPagerAdapter mSectionsPagerAdapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstFragment(), "ONE");
adapter.addFragment(new SecondFragment(), "TWO");
adapter.addFragment(new ThirdFragment(), "THREE");
viewPager.setAdapter(adapter);
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
and one of the fragment
public class FirstFragment extends Fragment{
public FirstFragment () {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
return view;
}
}
As you can see it's empty. Now, i need replace the fragments with the preferencefragment. But i can't understand how implement them with tabs. How can i do it?
Not too long ago, this would not have been possible, due to PreferenceFragments not working well with the support library. With the latest version of the support v7 library, we now have the PreferenceFragmentCompat class, which will work in an AppCompatActivity, and will also work with your ViewPager and FragmentPagerAdapter.
Since you're using support library fragments with android.support.v4.app.FragmentPagerAdapter, this is the only option with your current configuration.
Note that it is possible to use a TabLayout with non-support fragments, however you have to use the android.support.v13.app.FragmentPagerAdapter class, which does allow use of non-support fragments.
So to keep your current configuration and make it work, make your PreferenceFragment extend PreferenceFragmentCompat:
import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.view.View;
public class MySettingsPrefFragment extends PreferenceFragmentCompat {
public MySettingsPrefFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.fragment_settings_pref);
}
#Override
public void onCreatePreferences(Bundle bundle, String s) {
}
}
Add a new tab that corresponds to your PreferenceFragment:
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstFragment(), "ONE");
adapter.addFragment(new SecondFragment(), "TWO");
adapter.addFragment(new ThirdFragment(), "THREE");
adapter.addFragment(new MySettingsPrefFragment(), "SETTINGS"); //added
viewPager.setAdapter(adapter);
}
And, that should be it!

How to close the navigation drawer when an Item of ListView is selected?

I know that this question is asked many times but we have different situation. Regarding the project I downloaded the project navigation drawer demo from GitHub.com. Provided the code below:
this is the main activity:
package edu.ejapp.dotalegitstore;
#SuppressLint("NewApi")
public class MainActivity extends BaseActivity {
FragmentStackManager fm,sliding_menu;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
setUpView();
menuToggeleSetUp(savedInstanceState);
}
void setUpView(){
fm = new FragmentStackManager(this);
sliding_menu = new FragmentStackManager(this);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
fm.addFragment(new MainFragment(), R.id.main_frame, false, FragmentTransaction.TRANSIT_NONE, false);
sliding_menu.addFragment(new SlidingMenuFragment(), R.id.slide_fragment, false, FragmentTransaction.TRANSIT_NONE, false);
}
void menuToggeleSetUp(Bundle savedInstanceState){
mDrawerToggle = new ActionBarDrawerToggle(this, drawer,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name
) {
#SuppressLint("NewApi")
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
drawer.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_exit) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("COnfirm exit");
dialog.setMessage("Are you sure you want to exit?");
dialog.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
else if (id == R.id.action_login) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
else {
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The base activity extended by MainActivity:
package edu.ejapp.dotalegitstore;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
#SuppressWarnings("deprecation")
public class BaseActivity extends ActionBarActivity{
public ActionBarDrawerToggle mDrawerToggle;
public DrawerLayout drawer;
CharSequence mDrawerTitle;
CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActionBar();
}
public void setActionBar(){
getSupportActionBar().setTitle("");
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(this.getResources().getColor(R.color.app_main)));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
and lastly the sliding fragment activity, here the on item click is implemented not in baseactivity or main which is the reason of my problem: i cant close the drawer when i clicked item on the drawer:
public class SlidingMenuFragment extends Fragment {
List<String> data;
ListView list_view;
SlidingMenuListAdapter adapter;
#SuppressLint("InflateParams")
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_sliding_menu, null);
setUpView(root);
return root;
}
void setUpView(ViewGroup root){
list_view = (ListView)root.findViewById(R.id.list_view);
initList();
setUpClick();
}
void initList(){
data = new ArrayList<String>();
data.add("Home");
data.add("Arcana");
data.add("Courrier");
data.add("Hero Sets");
data.add("Immortals");
adapter = new SlidingMenuListAdapter(getActivity(),data);
list_view.setAdapter(adapter);
}
void setUpClick(){
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"Hi "+position,Toast.LENGTH_SHORT).show();
}
});
}
}
I didnt include the other files such as the xmls. My question is:
How can I close the drawer when I clicked item of the list view provided that the onitemclick is defined in SlidingMenuFragment class and the mDrawerlayout is located in BaseActivity class which is extended by MainActivity class?
create a method to close drawer in your main activity and call it from fragment.
public static void closeDrawer(){
if(drawerLayout.isDrawerOpen(leftDrawerList)){
drawerLayout.closeDrawer(leftDrawerList);
}
}
Inside Fragment
MainActivity.closeDrawer();
here is my suggestion:
provide an interface in SlidingMenuFragment like:
public class SlidingMenuFragment extends Fragment {
private OnListItemClickListener mOnListItemClickListener;
//here is mOnListItemClickListener getter and setter method
public *** set(get)OnListItemClickListener(){};
//define a interface here
public interface OnListItemClickListener{
public void onListenItemClick();
}
.
.
.
void setUpClick(){
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mOnListItemClickListener != null){
mOnListItemClickListener.onListenItemClick();
}
}
});
}
}
and then you should implement this interface in your MainActivity class like:
public class MainActivity extends BaseActivity {
void setUpView(){
fm = new FragmentStackManager(this);
sliding_menu = new FragmentStackManager(this);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
fm.addFragment(new MainFragment(), R.id.main_frame, false, FragmentTransaction.TRANSIT_NONE, false);
SlidingMenuFragment smFragment = new SlidingMenuFragment()
smFragment.setMonListItemClickListener(new OnListItemClickListener(){
public void onListenItemClick(){
drawer.close();
}
});
sliding_menu.addFragment(smFragment, R.id.slide_fragment, false, FragmentTransaction.TRANSIT_NONE, false);
}
}`

Categories