Android : Activity button shows up on fragment

open fragment from activity android example
how to open fragment from activity on button click in android
how to add fragment in activity in android example
how to call fragment from activity on button click in android
android fragment tutorial with example
add fragment to activity
activity and fragment in android
start fragment from activity

I have a simple application, with an Activity calling a Fragment.

Question I have is .. why is the Activity's button showing up on the Fragment ?

Seems to be a very simple problem .. just not able to pin point the issue !!

Activity screenshot :

Fragment Screenshot :

Notice that Activity's SUBMIT button shows up on the Fragment, but the TextView and EditText get hidden. Why ??

Activity :

package com.example.deep_kulshreshtha.toddsyndrome;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private TextInputEditText inputEditText;
    private EditText editText;
    private ToddSyndromeDBHelper dbHelper;
    private SQLiteDatabase db;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowHomeEnabled(true);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

//        inputEditText = (TextInputEditText) findViewById(R.id.lastNameEditText);
        editText = (EditText) findViewById(R.id.editText);

        Button submitButton = (Button) findViewById(R.id.submitButton);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CreateReportFragment fragment = CreateReportFragment.newInstance();

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.content_main, fragment, "CreateFragment");
                transaction.addToBackStack("CreateBackStack");
                transaction.commit();
            }
        });

        dbHelper = new ToddSyndromeDBHelper(this);

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(db != null) {db.close();}
    }

    public SQLiteDatabase getDb(){

        if(db == null) {
//            new ConnectionHelper().execute();
            db = dbHelper.getWritableDatabase();
        }
        return db;
    }

    public void viewPatientReport(View view){

        PatientReportFragment fragment = PatientReportFragment.
                newInstance(editText.getText().toString());

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_main, fragment, "SearchFragment");
        transaction.addToBackStack("SearchBackStack");
        transaction.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class ConnectionHelper extends AsyncTask<Void, Void, SQLiteDatabase>{

        @Override
        protected SQLiteDatabase doInBackground(Void... params) {
            db = dbHelper.getWritableDatabase();
            return db;
        }
    }
}

Activity xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Content xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/headline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="32dp"
        android:fontFamily="cursive"
        android:text="@string/todd_syndrome" />

<!--    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_last_name"
        android:layout_below="@id/headline"
        android:layout_centerHorizontal="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/lastNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/edit_text_hint" />
    </android.support.design.widget.TextInputLayout>-->

    <EditText
        android:id="@+id/editText"
        android:layout_below="@id/headline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edit_text_hint"/>

    <Button
        android:id="@+id/submitButton"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit"
        android:layout_below="@id/editText"
        android:onClick="viewPatientReport"/>

</RelativeLayout>

Fragment :

package com.example.deep_kulshreshtha.toddsyndrome;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class CreateReportFragment extends Fragment
        implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

//    private OnFragmentInteractionListener mListener;
    String name;
    boolean hallucegenicDrugs = false;
    int age;
    String gender;
    boolean migraine = false;

    private EditText editText;
    private Switch switchMigraine;
    private Spinner ageSpinner;
    private RadioGroup group;
    private Switch switchHall;
    private Button saveButton;

    private View.OnClickListener radioListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean checked = ((RadioButton)v).isChecked();
            gender = ((RadioButton)v).getText().toString();
        }
    };

    public CreateReportFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static CreateReportFragment newInstance(/*String param1, String param2*/) {
        CreateReportFragment fragment = new CreateReportFragment();
//        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
//        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
//            mParam1 = getArguments().getString(ARG_PARAM1);
//            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_create_report, container, false);

        editText = (EditText) view.findViewById(R.id.createPersonName);
        name = editText.getText().toString();

        switchMigraine = (Switch) view.findViewById(R.id.migraineToggle);
        switchMigraine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                migraine = false;
            }
        });

        ageSpinner = (Spinner) view.findViewById(R.id.ageSpinner);

        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= 100; i++){ list.add(i); }
        ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getContext(),
                android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        ageSpinner.setAdapter(adapter);
        ageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                age = (int) parent.getItemAtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        group = (RadioGroup) view.findViewById(R.id.genderButton);

        RadioButton maleRadio = (RadioButton) view.findViewById(R.id.radioMale);
        maleRadio.setOnClickListener(radioListener);
        RadioButton femaleRadio = (RadioButton) view.findViewById(R.id.radioFemale);
        femaleRadio.setOnClickListener(radioListener);

        switchHall = (Switch) view.findViewById(R.id.switchButton);
        switchHall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                hallucegenicDrugs = isChecked;
            }
        });

        saveButton = (Button) view.findViewById(R.id.saveButton);
        saveButton.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        int syndromePercentage = 0;

        Log.v("Deep", "Patient name : " + name);
        Log.v("Deep", "Has migraine : " + migraine);
        Log.v("Deep", "Patient age : " + age);
        Log.v("Deep", "Patient gender : " + gender);
        Log.v("Deep", "Drugs ? : " + hallucegenicDrugs);

        if(migraine == true){ syndromePercentage += 25; }
        if(age <= 15){ syndromePercentage += 25; }
        if(gender.equals("Male")){ syndromePercentage += 25; }
        if(hallucegenicDrugs == true){ syndromePercentage += 25; }

        SQLiteDatabase db = ((MainActivity)getActivity()).getDb();

        ContentValues values = new ContentValues();
        values.put(PatientTableContract.FeedEntry.COL_NAME_PATIENT_NAME, name);
        values.put(PatientTableContract.FeedEntry.COL_NAME_RISK, syndromePercentage);

        db.insert(PatientTableContract.FeedEntry.TABLE_NAME, null, values);

        Toast.makeText(getContext(), "Data saved successfully !", Toast.LENGTH_SHORT).show();

        editText.setText("");
        switchMigraine.setChecked(false);
        ageSpinner.setSelection(0);
        group.clearCheck();
        switchHall.setChecked(false);
    }

}

Fragment xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.CreateReportFragment"
    android:background="@android:color/white">

    <!-- TODO: Update blank fragment layout -->
    <android.support.design.widget.TextInputLayout
        android:id="@+id/nameLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/createPersonName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/edit_text_hint" />

    </android.support.design.widget.TextInputLayout>

<!--    <TextView
        android:id="@+id/migraineText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/nameLayout"
        android:text="@string/hint1"/>-->

    <Switch
        android:id="@+id/migraineToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hint1"
        android:layout_below="@id/nameLayout"
        android:checked="false"
        android:layout_margin="10dp"
        android:padding="10dp" />

    <TextView
        android:id="@+id/ageText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/migraineToggle"
        android:text="@string/hint2"
        android:layout_margin="10dp"/>

    <Spinner
        android:id="@+id/ageSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:prompt="@string/hint2"
        android:layout_below="@id/migraineToggle"
        android:layout_toRightOf="@id/ageText"
        android:layout_margin="10dp"
        android:layout_marginLeft="20dp"/>

<!--    <TextView
        android:id="@+id/genderText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/ageText"
        android:text="@string/hint3"/>-->

    <RadioGroup
        android:id="@+id/genderButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@id/ageSpinner"
        android:checkedButton="@+id/radioMale"
        android:layout_margin="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gender ?"
            android:layout_margin="10dp"/>

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Male"
            android:layout_margin="10dp"/>

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Female"
            android:layout_margin="10dp"/>
    </RadioGroup>

<!--    <TextView
        android:id="@+id/hallucinogenicText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/genderText"
        android:text="@string/hint4"/>

    <ToggleButton
        android:id="@+id/hallucinogenicToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/hallucinogenicText"
        android:hint="@string/hint4" />-->

    <Switch
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/genderButton"
        android:text="@string/hint4"
        android:checked="false"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/switchButton"
        android:text="Submit"
        android:layout_margin="10dp"/>

</RelativeLayout>

Second fragment xml :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.PatientReportFragment"
    android:background="@android:color/white">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/patientReport"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="40dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</FrameLayout>

Second Fragment :

package com.example.deep_kulshreshtha.toddsyndrome;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.deep_kulshreshtha.toddsyndrome.PatientTableContract.FeedEntry;


public class PatientReportFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    private MainActivity activity;

    private String[] projection = {FeedEntry._ID, FeedEntry.COL_NAME_PATIENT_NAME,
            FeedEntry.COL_NAME_RISK};
    private String selection = FeedEntry.COL_NAME_PATIENT_NAME + " = ?";

//    private OnFragmentInteractionListener mListener;

    public PatientReportFragment() {
        // Required empty public constructor
    }

    public static PatientReportFragment newInstance(String param1) {
        PatientReportFragment fragment = new PatientReportFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        TextView textView = (TextView) view.findViewById(R.id.patientReport);

        SQLiteDatabase db = ((MainActivity)getActivity()).getDb();
        Cursor cursor = db.query(FeedEntry.TABLE_NAME,
                projection,
                selection,
                new String[]{mParam1},
                null,
                null,
                null);

        if(cursor.getCount() == 0){
            textView.setText("No data found");
            return /*view*/;
        } else {
            cursor.moveToFirst();
            int riskPercent = cursor.getInt(cursor.getColumnIndex(FeedEntry.COL_NAME_RISK));

            textView.setText("Risk percentage : " + riskPercent );
            return /*view*/;
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_patient_report, container, false);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (MainActivity) context;
    }

}

When you bind your view in fragment it is always a better approach to bind it in the method onViewCreated() When you bind your view in onCreateView() you will face rendering issues. So bind your view in onViewCreated() method and the problem should be solved

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.name_of_layout,container,false);
    }



  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
        //bind your view here
    }

1.1: Creating a Fragment with a UI · GitBook, A Fragment can be a static part of the UI of an Activity , which means that the Fragment remains on the The FragmentExample app shows a fragment with radio buttons. Download the FragmentExample_start Android Studio project. This code sets up the View and the RadioGroup , and returns the View ( rootView ). When the button is clicked, you can add a fragment in some place in your activity layout. Or you can start a new activity which contains the fragment. Android Button OnClick Example. Android Multiple Fragments In One Activity Example. Android Add Fragment To Activity Dynamically Example. Android Fragment Communication With Activity Example


In the onCreateView of the fragment try adding this line

    View view = inflater.inflate(R.layout.fragment_name, container, false);
    view.setBackgroundColor(Color.WHITE);

I had a similar issue and fixed it using the above lines. Also, don't forget to add android:clickable="true" to your fragment_layout.xml parent layout.

Fragments, You can combine multiple fragments in a single activity to build a multi-pane UI Overview · Setting up the search interface · Storing and searching for data a fragment transaction (navigate backwards), by pressing the Back button. For example, a news application can use one fragment to show a list of  In this example, we will create a fixed space into the area of activity. In this fixed space, we will show up two fragments one by one. Meaning is that, one fragment will fill entire space when we click on the first button from activity. When we click the second button from activity, second fragment will entirely replace the first fragment. Step 1.


I've solved this by wrapping my button inside a LinearLayout.

Probable cause of the issue: It seems Button has higher z-index rendering when it comes to android and thus not wrapping it inside another layout renders the button higher than all other fragments.

<LinearLayout
    android:id="@+id/register_btn_wrapper"
    android:orientation="vertical"
    android:layout_below="@+id/splash_logo_img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/register_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/register"
        android:textSize="@dimen/text_big"
        android:paddingLeft="@dimen/btn_padding"
        android:paddingStart="@dimen/btn_padding"
        android:paddingRight="@dimen/btn_padding"
        android:paddingEnd="@dimen/btn_padding"
        android:layout_gravity="center"
        android:background="@color/app_color" />

</LinearLayout>

Hope this helps.

Dynamic Layouts using the Fragment Manager –, This code is part of the sample code is available from the Android SDK miles from the Bard's Stratford-Upon-Avon home, but in a different century) as a list view. The app has a number of activities and fragments in its design as shown in the specifying a fragment in the XML file using inside the activity's layout file; and. Androids materialistic designs uses Fragments instead of Activities.To create Fragments in your main project i.e Right click on the project folder -> New -> Fragments -> Fragment (Blank). is used as a container for FragmentsCode for Fragment Switching:


It's so wired to show only SUBMIT button on the top of page. I want to suggest you to add fragment instead of replace. please let me know the result after this.

FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_main, fragment, "SearchFragment");
fragmentTransaction.addToBackStack("SearchFragment");
fragmentTransaction.commitAllowingStateLoss();

How to launch a fragment from an activity on button click in Android , You don't launch a fragment, you load one to the activity's layout or replace an How can I remove the white screen that shows up when my Android app starts? One simple way to do this is to provide an Up button on the app bar for all activities except the main one. When the user selects the Up button, the app navigates to the parent activity. This lesson shows you how to add an Up button to an activity by declaring the activity's parent in the manifest, and enabling the app bar's Up button.


In your activity xml, add one more element, FrameLayout to host the fragment, like below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/headline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="32dp"
        android:fontFamily="cursive"
        android:text="@string/todd_syndrome" />

<!--    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_last_name"
        android:layout_below="@id/headline"
        android:layout_centerHorizontal="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/lastNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/edit_text_hint" />
    </android.support.design.widget.TextInputLayout>-->

    <EditText
        android:id="@+id/editText"
        android:layout_below="@id/headline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edit_text_hint"/>

    <Button
        android:id="@+id/submitButton"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit"
        android:layout_below="@id/editText"
        android:onClick="viewPatientReport"/>

   <!-- new layout to host fragment -->
   <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/fragment_holder"/>

</RelativeLayout>

and add your Fragment to that FrameLayout using.

Fragment button onclick, In Android, Fragment is a part of an activity which enable more modular We have looked at dialogs before where a dialog box pops up and floats over the UI​  DialogFragment is a specialized Fragment used when you want to display an overlay modal window within an activity that floats on top of the rest of the content. This is typically used for displaying an alert dialog, a confirm dialog, or prompting the user for information within an overlay without having to switch to another Activity.


Two fragments in one activity, A fragment represents a portion of user interface in an Activity, and provides a mechanism for creating android:layout_height="match_parent" ><Button Fragments are a powerful feature of good Android UI that allow you to approach app design in a modular manner. These are distinct views that can contain entire layouts and that come with their own accompanying Java code. By breaking your UI down this way,


Starting a fragment from an activity., How do I start a fragment from an activity using an ImageView? In the second activity I have two big buttons, each taking up half of the screen <​RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  The solution they came up with was Fragments. A fragment is a way of composing a part of an activity. It has it’s own life cycle, deals with it’s own inputs, and each activity can contain multiple fragments. The easiest way to see fragments in action is to create a new application and use the Master / Detail Flow. This creates an


Android Fragments Tutorial: An Introduction with Kotlin , In this Android Fragments with Kotlin tutorial you will learn the fundamental Use the Download Materials button at the top or bottom of this tutorial to download and extract the Starter Project. onDestroy : The fragment does its final clean up. When the activity comes back, its FragmentManager starts  Implementing same Options/Actionbar menu on all the Activities can be a tedious task, as you will need to write same code on all the activities. This example will help you to understand easy