want to play media a mp3 with imagebutton in fragment - android

I want to play a mp3 with ImageButton in Fragment.
here is my code:
public class FirstFragment extends Fragment {
View myView;
MediaPlayer mp;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.first_layout, container, false);
return myView;
ImageButton btn = (ImageButton)getView().findViewById(R.id.paratha);
//on click button for paratha
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer paratha = MediaPlayer.create(this, R.raw.paratha);
paratha.start();
}
});
}
}

You set your click listener below return statement. This is wrong, also the context should be getActivity() instead this in MediaPlayer, because you use fragment not an activity. Change your method like that:
View myView;
MediaPlayer mp;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.first_layout, container, false);
ImageButton btn = (ImageButton)myView.findViewById(R.id.paratha);
//on click button for paratha
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer paratha = MediaPlayer.create(getActivity(), R.raw.paratha);
paratha.start();
}
});
return myView;
}
Hope it help!

Your nextscreen() method should looks like that:
public void nextscreen() {
SecondFragment fragment = new SecondFragment();
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
You want to make intent but you need transaction to load you second fragment.

i want to move next screen, after mediaplayer finished the audio.
public class FirstFragment extends Fragment {
View myView;
MediaPlayer mp;
ImageButton btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.first_layout, container, false);
btn = (ImageButton) myView.findViewById(R.id.paratha);
//on click button for paratha
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer paratha = MediaPlayer.create(getActivity(), R.raw.paratha);
paratha.start();
paratha.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
nextscreen();
}
});
}
});
return myView;
}
public void nextscreen() {
Intent intent = new Intent(getActivity(), SecondFragment.class);
getActivity().startActivity(intent);
}
}
MainActivity file is here:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) 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, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
second_layout xml file:
public class SecondFragment extends Fragment {
View secView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
secView = inflater.inflate(R.layout.second_layout, container, false);
return secView;
}
}

Related

How do i retain Fragment's content while changing orientation in android?

I am using Navigation drawer layout and have 2 items in side menu. I used fragment for each item to show while navigate.
Let's consider Fragment1 & Fragment2. When i auto-rotate the screen from Fragment2, it destroy the fragment and showing Fragment1 's content.
With few youTube tutorials, I tried using onSaveInstanceState. But i was not able to find the correct solution.
JavaHomeActivity.java //Fragment1
public class JavaHomeActivity extends Fragment{
// created for save state in orientation change
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null)
{
}
else{
savedInstanceState.getString("home_text");
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Home");
}
// created for save state in orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("home_text", String.valueOf(R.id.nav_home));
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.java_home_layout,container,false);
}
}
JavaBasicActivity //Fragment2
public class JavaBasicActivity extends Fragment{
TextView text;
String data;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Java Basics");
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("basic_text", String.valueOf(R.id.nav_basics));
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.java_basic_layout,container,false);
if(savedInstanceState==null)
{
}
else{
data=savedInstanceState.getString("basic_text");
TextView myText= (TextView) view.findViewById(R.id.basicText);
myText.setText(data);
}
return view;
}
}
Fragment1's XML
<TextView
android:id="#+id/homeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="start"
android:padding="15dp"
android:text="#string/java_home_content"
android:textAlignment="textStart"
android:textColor="#color/text_color" />
Fragment2's XML
<TextView
android:id="#+id/basicText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="start"
android:drawableBottom="#drawable/jvm_arc"
android:padding="15dp"
android:text="#string/java_basic_content"
android:textAlignment="textStart"
android:textColor="#color/text_color" />
JavaMainPageActivity.java //navigation Drawer Activity
public class JavaMainPageActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_main_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
displaySelectedScreen(R.id.nav_home);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) 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.java_main_page, 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 displaySelectedScreen(int id){
Fragment fragment= null;
switch(id)
{
case R.id.nav_home:
fragment= new JavaHomeActivity();
break;
case R.id.nav_basics:
fragment= new JavaBasicActivity();
break;
}
if(fragment!=null)
{
FragmentTransaction ft= getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
displaySelectedScreen(id);
return true;
}
}
Can anyone please help me? Where i am doing error and which i have to change to get the solution.?
You are adding the Fragment in your onCreate through displaySelectedScreen(R.id.nav_home); and this gets executed even after orientation change.
So this overrides the actual system recreated Fragment.
Change the code like this in onCreate:
if (savedInstanceState == null) {
displaySelectedScreen(R.id.nav_home);
}
Here is your solution.
Your Fragment would look something like this:
public class Fragment1 extends Fragment {
private View mView;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// created for save state in orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("Fragment1", "My First Fragment");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_1, container, false);
return mView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView mText = (TextView) mView.findViewById(R.id.text);
if (savedInstanceState == null) {
} else {
String saved = savedInstanceState.getString("Fragment1");
mText.setText(saved);
}
}
}
And your activity should be like this :
public class MainActivity extends AppCompatActivity {
private Fragment mCurrentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
//Restore the fragment's instance
mCurrentFragment = getSupportFragmentManager().getFragment(savedInstanceState, "Fragment1");
} else {
mCurrentFragment = new Fragment1();
addFragment(mCurrentFragment);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "Fragment1", mCurrentFragment);
}
public void addFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
Fragment f = getSupportFragmentManager().findFragmentByTag(mCurrentFragment.getClass().getName());
if (f != null) {
fragmentTransaction.remove(f);
}
}
fragmentTransaction.add(R.id.fragment, fragment, fragment.getClass().getName());
fragmentTransaction.commit();
mCurrentFragment = fragment;
}
}
As it is already said that activity will recreate, you need to save your fragment's state too in your activity as in above code.
Hope it will help you and more clear to you.

Android Navigation Drawable send spinnern value to fragment

i have used navigation drawable from android studio 2.2.3 with fragments as frag1,frag2
I want to send selected spinner values to all fragments,
i have managed to send first selected spinner item to all fragments using bundle but when i select the second item from spinner item list
nothing work,here is my codes
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
String data1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) 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, menu);
ArrayList<String> list = new ArrayList<String>();
list.add("Top News");
list.add("Politics");
list.add("Business");
list.add("Sports");
list.add("Movies");
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list));
data1=spinner.getSelectedItem().toString();
Toast.makeText(MainActivity.this, spinner.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
switch (itemId) {
case R.id.nav_menu1:
fragment = new frag1();
break;
case R.id.nav_menu2:
fragment = new frag2();
Bundle data2 = new Bundle();
data2.putString("data", data1);
fragment.setArguments(data2);
break;
case R.id.nav_menu3:
fragment = new frag3();
Bundle data = new Bundle();
data.putString("data", data1);
fragment.setArguments(data);
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
public class frag2 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_3, container, false);
TextView text = (TextView) view.findViewById(R.id.textView3);
String getArgument = getArguments().getString("data");
text.setText(getArgument);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Menu 1");
}
}
So where and how can i modify or my codes so that
1.i can send the selected spinner item to all fragments ?
2.i can retain the state of selected spinner value when navigate between fragments ?
Use onItemSelected listener and perform operation you want to perform there
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Button Toggle not open drawer

I'm trying to put a tab to my app, created from scratch with the navigation drawer template with android studio, but I do not work the toggle button in Tab.class, to open the drawer, how do I get it?
MainActivity.class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) 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, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
startActivity(new Intent(this, TabActualJ.class));
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My Tab.class
public class TabActualJ extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
DrawerLayout mDrawerLayout;
#Override protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_actual_j);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(tb);
ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(drawer_toggle);
ab.setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getRootView().getWindowToken(), 0);
}
return super.onOptionsItemSelected(item);
}
#Override public boolean onCreateOptionsMenu (Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab_actual_j, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
activity_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
The problem is that you haven't asked the application to do anything inside MainActivity's onOptionsItemSelected
An example would be:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
pDrawerLayout.openDrawer(GravityCompat.START);
final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getRootView().getWindowToken(), 0);
return true;
}
return super.onOptionsItemSelected(item);
}
Edit:
Make DrawerLayout a global declaration like private DrawerLayout drawer;
and then initialize it once in your onCreate() so when you do drawer.openDrawers(..) you won't have to find a new instance of the DrawerLayout from your layout.

Android - TabLayout & ViewPager > Fragments > OnListFragmentInteractionListener

I'm new to Android and I started building a "Navigation Drawer Activity" project. I added a TabLayout and ViewPager to my activity_main.xml and now I can swipe between different lists. When I click an item in a list, it calls onListFragmentInteraction in my MainActivity.java. I tried the code below to dynamically add a Detail fragment when a user clicks an item in the list, but I get this error. My MainActivity class does "implement CustomerFragment.OnListFragmentInteractionListener"
First, is my attempt at showing a detail fragment inside a ViewPager correct? Would the code I am attempting below add a fragment in the current tab?
Secondly, does anyone know why I am getting this error?
Thanks so much!
Error:
java.lang.RuntimeException: com.myproject.android.MainActivity#186e12d
must implement OnFragmentInteractionListener
MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, TabLayout.OnTabSelectedListener, CustomerFragment.OnListFragmentInteractionListener, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private TabLayout tabLayout;
private ViewPager viewPager;
private Pager adapter;
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
#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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Customers"));
tabLayout.addTab(tabLayout.newTab().setText("Jobs"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.addOnTabSelectedListener(this);
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FirebaseMessaging.getInstance().subscribeToTopic("global");
String token = FirebaseInstanceId.getInstance().getToken();
// Check Google Play Services
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.build();
// test
Date d = new Date();
DbHandler dbHandler = new DbHandler(this, null, null, 1);
Customer customer = new Customer(1, 1, 1, 1, "Test", "Test", "Test", false, d, 1, d, 1);
dbHandler.addCustomer(customer);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
startActivity(new Intent(this, LoginActivity.class));
} else if (id == R.id.nav_gallery) {
startActivity(new Intent(this, SyncActivity.class));
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Customer List Fragment:
public class CustomerFragment extends Fragment {
private OnListFragmentInteractionListener mListener;
public CustomerFragment() {
}
#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_customer_list, container, false);
SearchView sv = (SearchView) view.findViewById(R.id.searchview);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
// Adapter
rv.setLayoutManager(new LinearLayoutManager(view.getContext()));
final CustomerAdapter adapter = new CustomerAdapter(getCustomers(), mListener);
rv.setAdapter(adapter);
// Search
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
//adapter.getFilter().filter(query);
return false;
}
});
return view;
}
private ArrayList<Customer> getCustomers() {
DbHandler dbHandler = new DbHandler(this.getActivity(), null, null, 1);
ArrayList<Customer> customers = dbHandler.getCustomers();
return customers;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction(Customer customer);
}
}
Customer Adapter:
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder> {
private final List<Customer> mValues;
private final OnListFragmentInteractionListener mListener;
public CustomerAdapter(List<Customer> items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_customer, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Customer customer = mValues.get(position);
holder.mItem = customer;
holder.mIdView.setText(String.valueOf(customer.getId()));
holder.mContentView.setText(customer.getCompanyName());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public Customer mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
UPDATE: It looks like I needed to add both onListFragmentInteraction AND onFragmentInteraction. The first is for the CustomerListFragment and the 2nd is for the CustomerDetailFragment.
And to get the CustomerDetailFragment working with the tabs, I followed this and got it working:
https://medium.com/#nilan/separate-back-navigation-for-a-tabbed-view-pager-in-android-459859f607e4#.lrjeexdcp
#Override
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
You need to put
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
Inside your MainActivity class instead of outside of it.
If that's not actually how your code is, edit your answer to break up the blocks to accurately represent how your code is built and include your interfance inside the fragment for the listener. You also may need the #Override tag above the onListFragmentInteraction implementation
Edit
As I mentioned above you need to put the #Override tag above the onListFragmentInteraction implementation, look at every other listener implementation you already have.

How to go back from Fragment to Fragment?

How I go to the previous fragment when I click on back button.
RecyclerAdapter_1_ten.java
public class RecyclerAdapter_1_ten extends RecyclerView.Adapter<RecyclerAdapter_1_ten.ViewHolder> {
private String[] SubTxt = {"NCERT Solution",
"Notes"};
private int[] SubImage = {R.drawable.ic_answers_black_48dp,
R.drawable.ic_notes_black_48dp};
Activity activity;
public RecyclerAdapter_1_ten(Activity activity) {
this.activity = activity;
}
class ViewHolder extends RecyclerView.ViewHolder {
public int currentItem;
public ImageView itemImage;
public TextView itemTitle;
public ViewHolder(View itemView) {
super(itemView);
itemImage = (ImageView) itemView.findViewById(R.id.SubImage);
itemTitle = (TextView) itemView.findViewById(R.id.SubTxt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
switch (position) {
case 0:
android.app.FragmentManager fm = activity.getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new SecondClass_10()).commit();
case 1:
Snackbar.make(v, "Comming Soon " + position,
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_1_9, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.itemTitle.setText(SubTxt[i]);
viewHolder.itemImage.setImageResource(SubImage[i]);
}
#Override
public int getItemCount() {
return SubTxt.length;
}
}
SecondClass_10.java
public class SecondClass_10 extends Fragment {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.second_class_10, container, false);
recyclerView = (RecyclerView) rootview.findViewById(R.id.recycler_ten_page_second);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter_2_ten();
recyclerView.setAdapter(adapter);
return rootview;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
android.app.FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new FirstClass_9()).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) 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, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
android.app.FragmentManager fn = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_9) {
fn.beginTransaction().replace(R.id.content_frame, new FirstClass_9()).commit();
} else if (id == R.id.nav_10) {
fn.beginTransaction().replace(R.id.content_frame, new FirstClass_10()).commit();
} else if (id == R.id.nav_11) {
fn.beginTransaction().replace(R.id.content_frame, new FirstClass_11()).commit();
} else if (id == R.id.nav_12) {
fn.beginTransaction().replace(R.id.content_frame, new FirstClass_12()).commit();
} else if (id == R.id.nav_aboutUs) {
} else if (id == R.id.nav_feedback) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I follow many Tutorial but I didn't get solution Hope I'll get answer here. I have added recyclerview when I click on it it open fragment but when I click on back button instead of going back it goes to first Page.
How to go back to Fragment from Fragment when I click on Back button?
You can use Stack for holding the fragment instances. When you move to the next fragment push the fragment into the stack and detach it from your activity and in the onbackpressed event pop the fragment and attach it to the activity.
This is one of the best explanation that i came across when i started in SO for fragment navigation i hope it helps clear your understanding of how they work.
Android fragments navigation and backstack

Categories

Resources