from the adapter of a RecyclerView which is contained in an Activity, i'm trying to launch a fragment when an element of the RecyclerView is pressed, this is my code right now :
#Override
public void onClick(View v) {
Intent intent;
int position = getAdapterPosition();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String onoff = preferences.getString("it's", "");
if (onoff.equalsIgnoreCase("on")) {
if (position == 0) {
CategoriesRecyclerView.fragSubreddit = "aww";
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
}
if (position == 1) {
CategoriesRecyclerView.fragSubreddit = "food";
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
}
if (position == 2) {
CategoriesRecyclerView.fragSubreddit = "funny";
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
}
if (position == 3) {
CategoriesRecyclerView.fragSubreddit = "gaming";
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
}
} else if (onoff.equalsIgnoreCase("off")) {
if (position == 0) {
CategoriesRecyclerView.fragSubreddit = "gaming";
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
}
if (position == 1) {
CategoriesRecyclerView.fragSubreddit = "funny";
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
}
if (position == 2) {
CategoriesRecyclerView.fragSubreddit = "food";
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
}
if (position == 3) {
CategoriesRecyclerView.fragSubreddit = "aww";
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
}
}
}
I Tested it launching some "testing activities" that i created, so i know that everything but the fragment launching works fine.
The error is here :
intent = new Intent(context, MainFragment.class);
context.startActivity(intent);
I'm launching the Fragment as it was an Activity, so when i run the app it crashes and tells me to declare the MainFragment as an activity in my manifest.
How can i launch that Fragment from my Activity?
Thanks very much.
You cannot start a Fragment with Intents so the method that I recommend to you is :
Fragment mFragment = null;
mFragment = new MainFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
For more information see Fragments Transactions documents
You can not start a Fragment using Intents. Intents provide a communication between activities.
If you want to launch a Fragment from other Fragment you have two options.
1- You can replace or add a new fragment.
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction
.replace( R.id.content_frame, fragment )
.addToBackStack( null )
.commit();
In this case The activity has two fragments.
2- You can launch a new Activity that contains a Fragment.
If you are using a Sections Pager Adapter, the simple thing to do would be using an onclick on image view or button like below:
In your starting activity (from where you want to go) use put extra to send some information to another activity
ivPhotoAlbums.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Send The Message Receiver ID & Name
Intent intent = new Intent(v.getContext(), PhotosActivity.class);
intent.putExtra("viewpager_position", 1);
v.getContext().startActivity(intent);
}
});
In your activity in which you want to land (at the end of your setupViewPager() function) catch that extra and use it as position
int position = 0;
Bundle extras = getIntent().getExtras();
if (extras != null) {
position = extras.getInt("viewpager_position");
}
viewPager.setCurrentItem(position);
Given the Assumption that your setupViewPager() function looks like below in your destination activity
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FriendsAlbumsFragment()); //index 0
adapter.addFragment(new MyAlbumsFragment()); //index 1
adapter.addFragment(new AddPhotosFragment()); //index 2
final ViewPager viewPager = findViewById(R.id.l_center_view_pager_view_pager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.l_top_tabs_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_friends_photos);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_my_photos);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_add_photos);
And Your SectionsPagerAdapter class looks like below (separate public class)
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return mFragmentList.get(i);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
}
And your center view pager layout is
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v4.view.ViewPager
android:id="#+id/l_center_view_pager_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="56dp">
</android.support.v4.view.ViewPager>
</merge>
Included in another file like this (or not included - in my case it was included)
<include layout="#layout/layout_center_viewpager" />
This will take you right from an activity to a fragment (in another activity) or from a fragment in one activity to a fragment in another activity...
Related
i have 3 fragments inside an activity, it's a swipe menu with tabs viewpager
how to get into second fragment from another activity ?
what i mean by second fragment is when iam using this standart intent
Intent i = new Intent(getBaseContext(),Form_Mhs_04.class);
startActivity(i);
it went to first intent (case 0)
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0 :
fragment = new form_mhs_04_fragment1();
break;
case 1 :
fragment = new form_mhs_04_fragment2();
break;
case 2 :
fragment = new form_mhs_04_fragment3();
}
return fragment;
}
You can't set 2nd fragment in TabLayout in this way. You have to pass the position that you want to select using intent.
Intent i = new Intent(this, Form_Mhs_04.class);
i.putExtra("TAB_POSITION", 2);
startActivity(i);
Then inside your Form_Mhs_04 activity get this position from intent and set TabLayout selected tab based on that.
int position = getIntent().getIntExtra("TAB_POSITION", 0);
TabLayout.Tab tab = tabLayout.getTabAt(position);
if(tab != null)
tab.select();
I want to handle onBackPressed in fragment
I use following code in my activity but this return 0
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
Toast.makeText(getBaseContext(), ""+count, Toast.LENGTH_SHORT).show();
if (count == 1) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
Just add .addToBackStack(null) in your Activity or Fragment . When you adding or replacing fragment. Like below
getSupportFragmentManager().beginTransaction().replace(R.id.parent_layout, new MyFragment()).addToBackStack(null).commit();
Note:- you don't have to do anything in your onBackPressed() method.
Just app this line when you want to replace any fragment and manage backsack on Fragment.
ClientHome per = new ClientHome();
Bundle bundle = new Bundle();
bundle.putString("usertype", "client");
per.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_from_left, R.anim.slide_to_right);
fragmentTransaction.replace(R.id.content_frame, per, "tag");
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
My app flow is:
Activity A -> Activity B (this activity has buttons which on click open fragments)
I want that when I am on Activity B's fragments, on back pressed the flow should be to Activity B and when I am on Activity B then on back pressed app should exit.
I am currently using:
#Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStackImmediate();
}
else {
super.onBackPressed();
}
}
It's working fine when back pressed on Activity B's fragments, but it's going to Activity A when pressed back from Activity B(and that too for some reason nothing is being displayed in Activity A).
EDIT
My code for calling fragment:
faqsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLoginSubmit.setVisibility(View.GONE);
Bundle b1 = new Bundle();
b1.putString("ComingFrom","Login");
android.support.v4.app.Fragment faqsFragment = new fragment11Faqs();
faqsFragment.setArguments(b1);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.framelayoutfaqs,faqsFragment);
transaction.addToBackStack(faqsFragment.toString());
transaction.commit();
}
});
You should call finish() when you call Activity B right after declaring its intent from ActivityA
Like this
Intent intent=new Intent(ActivityA.this,ActivityB.class);
startActivity(intent);
finish();
And you code for backstack is fine in activity b just add finish() after super.onBackPressed();
#Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStackImmediate();
}
else {
super.onBackPressed();
finish();
}
}
Here is how to add fragment to backstack
Fragment cameraEditing = new Editing(); FragmentManager
fragmentManager = getFragmentManager(); FragmentTransaction
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.cameraLayout,
cameraEditing,"cameraEditing");
fragmentTransaction.addToBackStack("cameraEditing");
fragmentTransaction.commit();
The issue i have is that if i leave the adapter as an inner class of the MainActivity.I have no issues, it loads properly. If I move it out to a separate java file, then instead of populating the detail view, it launches the details activity.
Constructor
public MoviesAdapter(MovieListActivity activity, List<DummyContent.DummyItem> items, boolean twoPane) {
mActivity = activity;
mValues = items;
mTwoPane = twoPane;
}
This is how I load the details view. its in an onClick() event.
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MovieDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MovieDetailFragment fragment = new MovieDetailFragment();
fragment.setArguments(arguments);
mActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.movie_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MovieDetailActivity.class);
intent.putExtra(MovieDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
Is this common functionality or am I missing something?
i am new to Andriod and programming. i am trying to make a to do list app, which will contain a listView, Button(add) in the main layout. when i click add i want it to go to another activity which will contain a editText and a add button. when i click the add button i want to update the list in my main activity. Now i was able to get the information from the second activity but when i try to add it in my list it over writes it.
How can i update my list as soon as my main activity appears again.
Here's what i have so far :
MainActivity class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add = (Button) findViewById(R.id.bAdd);
list = (ListView) findViewById(R.id.lvList);
addItems(); // i think this is the error but i dont know how to fix it.
alList = new ArrayList<String>();
aaList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, alList);
list.setAdapter(aaList);
}
public void clickAdd(View v) { //when clicking the add button(add)
Intent intent = new Intent(MainActivity.this, AddItem.class);
startActivity(intent);
}
private void addItems(){
String s = getIntent().getStringExtra("item");
aaList.add(s);
aaList.notifyDataSetChanged();
}
AddItem class :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_layout);
et = (EditText) findViewById(R.id.etAdd);
bt = (Button) findViewById(R.id.badd);
}
public void add(View v){ //when clicking the add button(bt)
edit = et.getText().toString();
Intent intent = new Intent(AddItem.this, MainActivity.class);
intent.putExtra("item", edit);
startActivity(intent);
}
Can you please tell me where and why i am going wrong? Thank You
First of all, you should use startACtivityForResult
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
Then in your second Activity
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
And back in your fist one:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
and then, your addItem should do the trick:
private void addItems(String s){
aaList.add(s);
aaList.notifyDataSetChanged();
}