Create Simple Fragment with button in Android Studio

Objective:
To create a simple fragment with button

Function:
Text View from fragment is changed when the button is pressed.

IDE:
Android Studio 1.0.2

Source Code:
The project can be downloaded from here.

Result:



Content of MainActivity.java file:
package com.example.osdevlab.simplefragmenttutorial;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;


public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //set to activity_main.xml

        /*way of adding fragment with java*/
        //FragmentOne is the class which inflate the fragment_one.xml and return the view
        FragmentOne myFragment = new FragmentOne();
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        //'container' is android id in activity_main.xml
        //add android:id="@+id/container" in activity_main.xml
        transaction.add(R.id.container, myFragment, "main_layout_container");
        transaction.commit();
    }
}


Content of FragmentOne.java file:

package com.example.osdevlab.simplefragmenttutorial;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by osdevlab on 12/29/14.
 */
public class FragmentOne extends Fragment {


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

        // Inflate the layout with fragment_one.xml
        View view = inflater.inflate(R.layout.fragment_one, container, false);

        //create Button 'buttonPress' and link with button id from fragment_one.xml
        Button buttonPress = (Button) view.findViewById(R.id.button);
        //create TextView 'textViewPress' and link with texView id from fragment_one.xml
        final TextView textViewPress = (TextView) view.findViewById(R.id.textView);

        /*define OnClickListener here*/
        buttonPress.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //when button is pressed, textViewPress is changed to following message
                textViewPress.setText("Button has been Pressed");
            }
        });

        return view;
    }


}

No comments:

Post a Comment