i try to change the view of my App using a Fragment. I tried on this several days, so i made a clean code to present my problem. I have an MainActivity with a OptionsMenu, in this OptionsMenu i have an item called "action_connect". The first view of my App should display "welcome to MainActivity!". When someone clicks the "action_connect" item, I want the View to change to my Fragment in which "welcome to Fragment!" should be displayed. Problem: The Fragment overlays the Activity Text instead of switching to the new view.
I hope you can help me to solve this. Thanks in advance.
Heres my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.main_activity);
}
@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, 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.
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
MainActivityFragment mMainActivityFragment = new MainActivityFragment();
int id = item.getItemId();
if (id == R.id.action_connect) {
ft.replace(R.id.default_container, mMainActivityFragment);
}
ft.commit();
return super.onOptionsItemSelected(item);
}
Fragment:
public class MainActivityFragment extends Fragment{
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_connect, parent, false);
return rootView;
}
}
Fragment-XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Welcome in Fragment!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
Activity-XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<FrameLayout
android:id="@+id/default_container"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
<TextView
android:text="Welcome in MainActivity!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
</RelativeLayout>