I have a store item fragment in the navigation drawer item menu in this fragment I will like to known how to add another fragment to it if the user click on the Imageview icon then still maintain my navigation drawer below is my try
package com.example.entertainmentlab.ui.store;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.entertainmentlab.R;
import com.example.entertainmentlab.ui.setting.SettingViewModel;
public class StoreFragment extends Fragment {
private StoreViewModel StoreViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
StoreViewModel =
ViewModelProviders.of(this).get(StoreViewModel.class);
View root = inflater.inflate(R.layout.fragment_store, container, false);
final ImageView MusicButton = root.findViewById(R.id.music_btn);
//I want to move to the next Fragment if the user click the music icon
MusicButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Fragment fragment = new BlankFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_store, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}catch (Exception e ){
Toast.makeText(getActivity(), "erro "+e, Toast.LENGTH_SHORT).show();
}
}
});
// StoreViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
// #Override
// public void onChanged(#Nullable String s) {
// textView.setText(s);
// }
// });
return root;
}
}
if the user click the image icon I want to send he/she to the music fragment and then still maintaining the drawer and allow him to return back to the previous fragment
i suggest to you use a AlertDialog for do this work but you can make full screen AlertDialog...
Related
I'm trying to build a food menu app for my school. I will be entering the meal plan every week into a MySQL database. My app has a tabbed view with each fragment representing the day of the week.
I want to be able to display the corresponding day's menu on the corresponding fragment.
MainActivity.java
package me.anshsehgal.lunchmenu;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter; //make all the variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
viewPager = (ViewPager)findViewById(R.id.viewPager); //reference them
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new HomeFragment(),"M");
viewPagerAdapter.addFragments(new MondayFragment(),"Tue");
viewPagerAdapter.addFragments(new TuesdayFragment(),"W");
viewPagerAdapter.addFragments(new WednesdayFragment(),"Thu");
viewPagerAdapter.addFragments(new ThursdayFragment(),"F"); //adding fragments to view page adapter
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
RelativeLayout main_view = (RelativeLayout)findViewById(R.id.anshLayout);
switch (item.getItemId()){
case R.id.action_settings:
if(item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
Intent i = new Intent(this,Settings.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
MondayFragment.java
package me.anshsehgal.lunchmenu;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class MondayFragment extends Fragment {
public MondayFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_monday, container, false);
}
}
Screenshot of app
Sample of the layout
Sample entry in table
It is not advisable to access my sql directly in Android applications. You need to build rest API's which will expose required data in compressed manner(JSON). You can use any of the programming language like Java/C#/Scala/Node to expose rest end points.
If you are trying to store data which is user specific then you can use sql lite database
I am trying to create an activity which holds two fragments. One fragment is displayed when the activity starts and the other one is displayed when the user press a button in the toolbar.
In the second fragment I want to add back navigation and when the user press the back button the second fragment should close and the first one should appear.
But I am getting some errors and I couldn't fix them.
MainActivity.java
package com.geapps.notapp.activities;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import com.geapps.notapp.R;
import com.geapps.notapp.fragments.MainFragment;
import com.geapps.notapp.fragments.NewNoteFragment;
public class MainActivity extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
loadFragment(new MainFragment(), "Main");
}
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle("Toolbar");
toolbar.inflateMenu(R.menu.main);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener()
{
#Override
public boolean onMenuItemClick(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.action_new:
loadFragment(new NewNoteFragment(), "New Note");
break;
}
return false;
}
});
}
public void loadFragment(Fragment fragment, String tag)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_container, fragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
}
}
MainFragment.java
package com.geapps.notapp.fragments;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.geapps.notapp.R;
import com.geapps.notapp.adapters.NotesListAdapter;
import com.geapps.notapp.models.Note;
public class MainFragment extends Fragment
{
private View view;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_main, container, false);
loadNotes();
return view;
}
private void loadNotes()
{
ListView notesList = (ListView)view.findViewById(R.id.notes_list);
ArrayList<Note> notes = new ArrayList<Note>();
notes.add(new Note("Sunday homework", "1. Do math homework and then sleep"));
notes.add(new Note("Job details", "Programming job especially iOS and Android development"));
notes.add(new Note("Journal Part 1", "What am I going to do now? I have no way to run .. :("));
NotesListAdapter notesListAdapter = new NotesListAdapter(this.getActivity(), notes);
notesList.setAdapter(notesListAdapter);
}
}
NewNoteFragment.java
package com.geapps.notapp.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.geapps.notapp.R;
public class NewNoteFragment extends Fragment
{
private View view;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_new_note, container, false);
Toolbar toolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
toolbar.getMenu().findItem(R.id.action_new).setVisible(false);
toolbar.setNavigationIcon(R.drawable.ic_action_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.popBackStack("Main", FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
});
return view;
}
}
And here are the errors:
PathClassLoader(BaseDexClassLoader).findClass(String) line: 61
PathClassLoader(ClassLoader).loadClass(String, boolean) line: 501
PathClassLoader(ClassLoader).loadClass(String) line: 461
BackStackRecord.getEnterTransition(Fragment, boolean) line: 1056
BackStackRecord.configureTransitions(int, BackStackRecord$TransitionState, boolean, SparseArray, SparseArray) line: 1138
BackStackRecord.beginTransition(SparseArray, SparseArray, boolean) line: 1029
BackStackRecord.popFromBackStack(boolean, BackStackRecord$TransitionState, SparseArray, SparseArray) line: 883
FragmentManagerImpl.popBackStackState(Handler, String, int, int) line: 1593
FragmentManagerImpl$3.run() line: 509
FragmentManagerImpl.execPendingActions() line: 1489
FragmentManagerImpl$1.run() line: 454
Handler.handleCallback(Message) line: 615
FragmentActivity$1(Handler).dispatchMessage(Message) line: 92
Looper.loop() line: 137
ActivityThread.main(String[]) line: 4921
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 511
ZygoteInit$MethodAndArgsCaller.run() line: 1038
ZygoteInit.main(String[]) line: 805
NativeStart.main(String[]) line: not available [native method]
Try using this
getActivity().getSupportFragmentManager().popBackStack();
Instead of making it custom, let the system handle itself. Make following changes and give it a try:
public void loadFragment(Fragment fragment, String tag)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_container, fragment, tag);
// fragmentTransaction.addToBackStack(tag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
and
toolbar.setNavigationOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
// fragmentManager.popBackStack("Main", FragmentManager.POP_BACK_STACK_INCLUSIVE);
// fragmentManager.popBackStack();
getActivity().onBackPressed();
}
});
Although very late but for an easy approach try this:
When you add your first fragment into your activity call addToBackStack(null) before you commit.This will allow users from second fragment to return the first Fragment by back button.
getFragmentManager().beginTransaction().replace(R.id.main_container, fragment).addToBackStack(null).commit();
Now Add this in your second fragment's on click method to remove second fragment and return to first fragment.
getActivity().getFragmentManager().beginTransaction().remove(this).commit();
//now recreating main activity to return to first fragment
getActivity().recreate();
Alternate and better aproach is using interface see android docs here
Try this anyone of this three methods
1.#
getActivity().getSupportFragmentManager().popBackStack();
2.#
getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
3.#
getActivity().getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
I tried to have a view of an ActionBarActivity opening after hitting a spinner button.
There are two items on my spinner, the second one runs fine, but when I tried to access the Categorias item the app throws me a NullPointerException inside the DrawerActivity class. I don't actually know where the problem is. Another ActionBarActivity extension class that I have runs perfectly.
I'm new to Android/Java development.
The Spinner Fragment
import inmostla.ligatangamanga.pruebaintegrar.navigationdrawer.NavigationDrawerActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerFragment extends Fragment {
private static Spinner spinner;
private int selected;
private View mView;
static void setSpinnerContent( View view ){
spinner = (Spinner) view.findViewById(R.id.spinner1);
return ;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_spinner, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
/**
* Maneja las acciones seleccionadas del Spinner
*/
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
selected = spinner.getSelectedItemPosition();
switch(selected){
case 1:
Intent categorias = new Intent( );
categorias.setClass( getActivity() , NavigationDrawerActivity.class );
startActivity(categorias);
break;
case 2:
Intent convenios = new Intent();
convenios.setClass(getActivity(), ConveniosFragment.class);
startActivity(convenios);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
return view;
}
}
The Navigation Drawer Activity extends a ActionBarActivity
package inmostla.ligatangamanga.pruebaintegrar.navigationdrawer;
import inmostla.ligatangamanga.pruebaintegrar.navigationdrawer.NavigationDrawerFragment;
import inmostla.ligatangamanga.pruebaintegrar.R;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class NavigationDrawerActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}...
Maybe that's because getActivity() returns null. Try overriding onAttach() and keep Activity reference as a field in your class. Use this reference instead of getActivity() when you needed a reference to context or activity.
I am new to android and am following the tutorial at Dartmouth. http://www.cs.dartmouth.edu/~campbell/cs65/lecture08/lecture08.html
I am following all the codes and at the MainActivity.java,
// create the fragments
Fragment mFindFragment = new FindFragment();
Fragment mChatFragment = new ChatFragment();
// bind the fragments to the tabs - set up tabListeners for each tab
mFindTab.setTabListener(new MyTabsListener(mFindFragment,
getApplicationContext()));
mChatTab.setTabListener(new MyTabsListener(mChatFragment,
getApplicationContext()));
I have encountered this error: Type mismatch: cannot convert from FindFragment to Fragment. So I follow the fix error suggestions and change the code to
// create the fragments
FindFragment mFindFragment = new FindFragment();
// bind the fragments to the tabs - set up tabListeners for each tab
mFindTab.setTabListener(new MyTabsListener(mFindFragment,
getApplicationContext()));
Now, there is a new error: The constructor MyTabsListener(FindFragment, Context) is undefined.
Just in case the imports are critical, here they are:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
For myTabsListener:
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public Context context;
public MyTabsListener(Fragment fragment, Context context) {
this.fragment = fragment;
this.context = context;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Reselected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Selected!", Toast.LENGTH_SHORT).show();
ft.replace(R.id.container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Unselected!", Toast.LENGTH_SHORT).show();
ft.remove(fragment);
}
}
For my FindFragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FindFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.findfragment, container, false);
}
}
I am pretty confused here. I am not sure if this is related to my import, lib setup or other problems. Thanks in advance!
You need to change this
import android.support.v4.app.Fragment;
// you will use this import when you want fragment from support library
// in that case you will extend FragmentActivity which is the base class for support based fragments
to
import android.app.Fragment;
in FindFragment.java.
Similarly do the same in ChatFragment.java also
I have used actionbar and it is working fine. I have four fragment in the actionbar. I want to implement tabhost in one of the fragment. I have used the following code.
package com.main.udebate;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class Info extends Fragment {
public Info() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
private TabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent i = new Intent(Info.this, about.class);
View view = inflater.inflate(R.layout.info, container, false);
mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
mTabHost.setup();
TabHost.TabSpec tab = mTabHost.newTabSpec("my tab content");
tab.setIndicator("my tab content");
tab.setContent(i);
mTabHost.addTab(tab);
mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
return view;
}
}
I am getting error on Intent i = new Intent(Info.this, about.class); line as The constructor Intent(Info, Class) is undefined.
About.java
package com.main.udebate;
import android.app.Activity;
import android.os.Bundle;
public class about extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
}
}
Can someone pls help me to set tabhost inside fragment.
Thanks,
try to use this
Intent i = new Intent(getActivity(), about.class);
instead of this line
Intent i = new Intent(Info.this, about.class);
As Info.this does not mean any context thats why you get "The constructor Intent(Info, Class) is undefined." this error.
In fragment where you use this reference you should instead use getActivity() reference