how to get back to fragment from activity? - android

I have four fragments in an Activity C. they are behaving as tabs. I have to go from a fragment to a new Activity X. Now i want to come back to fragment from Activity X to fragment.
here is my main activity
'public class MainInterface extends ActionBarActivity {
ViewPager pager;
PagerTabStrip tab_strp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_interface);
MainPagerAdapter mapager = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(mapager);
tab_strp = (PagerTabStrip) findViewById(R.id.tab_strip);
//tab_strp.setTextColor(Color.WHITE);
//tab_strp.setTextSize(14,14);
//tab_strp.setTabIndicatorColor(Color.WHITE);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2196f3")));
getSupportActionBar().setTitle("Instructor");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
'
here is activity
'public class Discussions extends Fragment implements View.OnClickListener {
ImageButton post;
TextView dTitle;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.discussions,container,false);
post=(ImageButton)view.findViewById(R.id.ibDisc);
post.setOnClickListener(this);
dTitle=(TextView)view.findViewById(R.id.tvDiscTitle);
return view;
}
#Override
public void onClick(View view) {
Intent in=new Intent(getActivity(),PostDiscussion.class);
startActivity(in);
}
}'

Save the name of your fragment in sharedPreferences before navigating to new activity and onBackpressed of that new activity or when you want to come back to same fragment get the name from SharedPreferences and add that particular fragment to the earlier activity

Related

Navigation Drawer Activity move from fragments to activities and return

I have a navigation drawer activity with fragments and I will send each fragment to an activity. I have a problem if I select option 3 of my menu that is a fragment that will send me to an activity, but when I return with the Back button, it sends me to option 1, what I want is that I return to option 3.
How can I change this?
I tried to do it by parentActivity but it did not work
Thank you.
My navigation drawer activitywithfragments
When I click on the button, it sends me to an activity that is this
And in the activity I have a toolbar to return and what I want is to return to option 3 and not to 1.
What do I need to do in my code or what can I place?
My fragment code option 3
public class Mis_Aliados extends Fragment {
Button boton;
public Mis_Aliados() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.persona_mi_perfil, container, false);
boton=view.findViewById(R.id.buton);
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ActividadEx.class);
startActivity(intent);
}
});
return view;
}
}
My activity code
public class ActividadEx extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pruebaactividad);
Toolbar toolbarback=findViewById(R.id.include);
setSupportActionBar(toolbarback);
getSupportActionBar().setTitle("Activity");
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
In your ActividadEx add this method to handle toolbar back button press
I'm putting 1 intent extra to make sure you want to open Option 3 when you are back to Navigation drawer Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, NavgationDrawerActivity.class);
intent.putExtra("openOption3", true);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
On NavigationDrawerActivty inside onCreate()
you can check if Bundle has data or not. If its empty you can open Option1 fragment.
If it has data check it. and open Option3 Fragment.
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.getBoolean("openOption3", false)) {
//Use Fragment Transaction to Open Option 3 Fragment
} else {
//Open Option 1 Fragment Or any other Fragment
}
} else {
//Open Option 1 Fragment Or any other Fragment
}
Feel free to comment if you've any queries.

How to start new activity inside viewpager tab

I am coding a tabbed app in android using ViewPager. Currently, I have an activity, called RSC Activity, that I want to open up inside a tab. (RSCActivity implements onCreateView and has a UI of its own). My main problem is a button that has a click listener set in RSCActivity, cannot be implemented in the tabbed layout, because the click listener method is a method of a class extended from RSC Activity.
Code-
I start RSCActivity with the MainActivity:
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
protected void onCreate(Bundle savedInstanceState) {
..
Intent intent = new Intent(getActivity(), RSCActivity.class);
startActivity(intent);
..
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2= new Tab2();
return tab2;
case 2:
Tab3 tab3= new Tab3 ();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab1";
case 1:
return "Tab2";
case 2:
return "Tab3";
}
return null;
}
}
public static class Tab1 extends Fragment{
public Tab1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.activity_rsc, container, false);
return rootView;
}
}
}
In the RSCActivity, I set the view and click listener like so,
public class RSCActivity extends BleProfileServiceReadyActivity<RSCService.RSCBinder> {
...
#Override
protected void onCreateView(final Bundle savedInstanceState) {
setContentView(R.layout.activity_feature_rsc);
final Button connectButton = (Button) findViewById(R.id.action_connect);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//connectButton.setText("Clicked");
onConnectClicked(v);
}
});
}
...
}
If I don't call setContentView in RSCActivity, then I am not able to set the click listener, because onConnectClicked is part of RSCActivity, but this opens up a separate screen outside of the tabbed view. So as it stands now, I have to open a new screen to click CONNECT, but I want the UI to open up in Tab1 and be able to click CONNECT.
As mentioned, I cannot move the onConnectClicked into MainActivity. Going the route of making the activity into a service doesn't seem feasible, because RSCActivity extends another activity, which in turn extends another activity, etc. I need RSCActivity to be running when I am inside Tab1.
Thanks in advance

How to change the behaviour of back button in Android fragment

The action of back button is bring back to the previous page.
How to change the action of back button in Android fragment, for example:
if( click back button ) then
Toast.maketext("text");
my code is :
public class Rechercher extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* pour creer le fragment */
view = inflater.inflate(R.layout.rechercheavance, container, false);
return view;
}
}
From the Activity, override the onBackPressed() method for custom back press action. Hold an instance of the fragment when you attach it and use a public method in the fragment for doing something from the fragment by calling it from the onBackPressed() method.
Activity
SomeFragment fragment;
#Override
public void onCreate(Bundle savedInstanceState) {
...
//Create the fragment instance
fragment = new SomeFragment();
//Now add the fragment to the layout
}
...
#Override
public void onBackPressed() {
//Called when back pressed
fragment.doSomething();
}
And in the Fragment define the method doSomething
public void doSomething() {
//custom action
}

Navigation Drawer AsyncTask

I would like to expose my problem and I want to know how I could solve it.
In my application I'm using an activity, making a simple login, launching a asyncTask. At the end of this task, the user is redirected to another activity, which is the home activity of application. The latter has the task of managing a navigation drawer and its fragments. The contents of each fragment must be populated with data retrieved from a server and the navigation drawer set the default fragment F1, which is displayed after the user has logged on.
Now the problem is:
How can I recover the data necessary to populate the listView contained in fragment1?
I know how to implement an adapter for the listView, but I don't understand how to communicate the home activity with the fragment F1. My intention would be to retrieve a circular dialog (content in F1) and run it as long as the data required for the adapter have not been recovered.
Here some code:
public class LoginActivity extends ActionBarActivity {
private Button loginButton;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Login().execute();
}
};
}
#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 class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Login");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (progessDialog.isShowing()) {
progressDialog.dismiss();
}
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
Bundle bundle = new Bundle();
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected Void doInBackground(String... params) {
// code to retrieve data.
}
}
}
public class HomeActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar toolbar;
private FragmentDrawer fragmentDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(false);
fragmentDrawer = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
fragmentDrawer.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
fragmentDrawer.setDrawerListener(this);
// Here the problem!!!
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, 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 displayView(int position) {
switch (position) {
case 0:
Fragment fragmentOne = new FragmentOne();
move(matchFragment);
break;
case 1:
Fragment fragmentTwo = new FragmentTwo();
move(teamFragment);
break;
case 2:
Fragment fragmentThree = new FragmentThree();
move(myTeamFragment);
break;
case 3:
//other fragment....
default:
break;
}
}
public void move (Fragment fragment) {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment, fragment.getClass().getSimpleName());
fragmentTransaction.commit();
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
}
public class FragmentOne extends Fragment {
private ListView listView;
private ArrayList<Info> infos;
private InfoAdapter infoAdapter;
public FragmentOne() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_match, container, false);
listView = (ListView) rootView.findViewById(R.id.match_list_view);
return rootView;
}
}
Now, where do I implement the AsyncTask to retrieve data for adapter? In fragment or the Activity?
If it were the Activity, how can I recover the elements of view of fragment?
Thanks in advance and sorry for bad english.
for your first quesiton:
I don't understand how to communicate the home activity with the
fragment F1
You can pass information from HomeActivity to the Fragment through parameters passed to the Fragment's constructors. So instead of Fragment fragmentOne = new FragmentOne();, you can call Fragment fragmentOne = new FragmentOne(A a); where a is data you want to pass to the fragment. Of course, you need to add in the constructor with parameters to the Fragment class.
For the 2nd point:
Now, where do I implement the AsyncTask to retrieve data for adapter?
In fragment or the Activity? If it were the Activity, how can I
recover the elements of view of fragment?
You can put AsynchTask call inside onCreate() to load data for the listView...etc. Another option which I prefer is to use Loaders. Please see this documentation on Loaders here http://developer.android.com/guide/components/loaders.html. It also has an example.
For explanation and sample, you can follow these 4-part tutorials:
http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html.

Getting value from Fragment into mainActivity

I have a MainActivity. It's layout contains a fragmentContainer and an actionBar. Then I have 2 different fragments containing various EditTexts.All of them have Ids. I populate the fragmentContainer with the fragments when user clicks a button in actionBar. Everything works perfectly.
Now...the app, is supposed to collect the contents of all EditTexts from both fragments when I push a button (in the menu of the actionBar). But it does not work. It crashes when I try to access the EditTexts directly from the activity. I understand that I should create a public method inside the code of the fragments that will return the values I am interested in. But I seem to be doing something wrong because the method is not accessible from the main (TabActivity)
Here is my code:
public class TabActivity extends Activity {
ActionBar.Tab tab_alocare, tab_merc;
Fragment fragmentTab1 = new aloc_fragment();
Fragment fragmentTab2 = new merc_fragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab); // this layout contains the fragmentContainer
...// here I do some actionBar stuff
}
...
}
An example of one of the fragments is bellow:
public class aloc_fragment extends Fragment {
EditText mEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_aloc, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mEditText = (EditText) getView().findViewById(R.id.edaloc);
}
public String getMyText() {
String rez = "";
if (mEditText.getText()!=null) {
rez = mEditText.getText().toString();
}
return rez;
}
}
Now... if inside the Activity code I want to access the edaloc EditText using findViewById, it crashes the app with nullException. So I then tried to access the public method of the fragment so that it would return me the value that I need. But "getMyText" method is not accessible from the TabActivity.
So, this code does not work:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
Fragment alocfragment = (Fragment) getFragmentManager().findFragmentByTag("aloc");
String s = alocfragment.getMyText(); // this is not compiling at all
I am clearly doing something wrong.
Please advise.
Thank you
There are lots of mistakes in your code, You have neither declared nor initialize the fragments at proper place. Also, you are trying to create another instance of fragment in onOptionsItemSelected which is wrong, you need to use same instance of fragment there to access your functions with values. I hope you know how to add and inflate fragment. See my comments and code changes.
Try with this -
public class TabActivity extends Activity {
ActionBar.Tab tab_alocare, tab_merc;
//Declare fragments here
Fragment fragmentTab1;
Fragment fragmentTab2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab); // this layout contains the fragmentContainer
//Initialize here
fragmentTab1 = new aloc_fragment();
fragmentTab2 = new merc_fragment();
//inflate/add fragments here to the activity
...// here do your actionBar stuff
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
//Now, use same instance of fragment to access your function
String s = fragmentTab1.getMyText();
}
}
public class aloc_fragment extends Fragment {
EditText mEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_aloc,
container, false);
//hold edittext here in the variable
mEditText = (EditText) view.findViewById(R.id.edaloc);
return view;
}
public String getMyText() {
String rez = "";
if (mEditText.getText()!=null) {
rez = mEditText.getText().toString();
}
return rez;
}
}
Also, must to go through Fragment tutorial on Android Developer Fragment Link Link 2, Using Fragments

Categories

Resources