Error404 Error404 - 3 months ago 11
Android Question

How can I start an Activity from a Fragment?

I would like to start an

Activity
from a
Fragment
when I press a button on the last one but I am getting a blank layout instead of the layout that is associated to the
Activity
.

I call the
Fragment
from
MainActivity.class
like this:

FragmentManager mFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.mainContent,new FragmentMain()).commit();


And on
FragmentMain
class I have an
onClick
method like follows:

@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), FinalClass.class);
getActivity().startActivity(intent);
}


but the result is a blank layout and no errors are shown on the logcat. I have searched on the web for similar behaviours and I found some solutions that did not resolve my problem:



I do not have any method
addToBackStack()
on my project so this solution does not work for me.



getActivity().startActivity(myIntent)
is the accepted answer.

The ways that they use to start the Activity from the Fragment does not change from the way I am using.



Any of the solutions provided worked for me.

P.S: I have declared the
Activity
on the
Manifest.xml
file:

<activity
android:name=".FinalClass"
android:screenOrientation="portrait"
android:label="Final Class"
android:icon="@mipmap/ic_launcher"
android:theme="@style/AppTheme.NoActionBar" />


P.S.2: Do not doubt to ask if you need more code (I tried to simplify it to focus on the problem).

What can I do to avoid that the
Activity
gives to me a blank layout instead of the layout associated to that
Activity
?

Thanks in advance!

Answer

Set your layout in activity like this in onCreate

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_final_class);
}

dont use onCreateView for activity

Comments