Fragment
has a method calledonCreateView(LayoutInflater, ViewGroup, Bundle)
. Override it, inflate using the layout and return the view.- Since create method expects a
Context
, pass it usinggetActivity()
findViewById(int)
can be called asgetView().findViewById(R.id.button3)
Here is a sample code:
public class Rajathmusic extends Fragment {
private static final String TAG = "MyActivity";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.v(TAG, "Initializing sounds...");
final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.rajath);
View v = getView();
Button play_button = (Button) v.findViewById(R.id.button3);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
Log.v(TAG, "Sounds initialized.");
}
}
Read more about Fragment
lifecycle here to know why I’ve put the code in onActivityCreated
and not onCreate