This question already has answers here:
How to set onclick listener for a button in a fragment in android
(3 answers)
Closed 4 years ago.
I want to control button from fragment xml file in the fragment activity. In other activity we can easily control our button by findviewbyid method and after that we can apply setonclicklistener. But here in fragment how do i access the button and apply onclicklistener method.
My Fragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
/**
* A simple {#link Fragment} subclass.
*/
public class QuoteTypeFragment extends Fragment {
public QuoteTypeFragment() {
// Required empty public constructor
}
LinearLayout typeOne, typeTwo, typeThree, typeFour;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
return vv;
}
}
My Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#3f525e"
tools:context=".QuoteTypeFragment">
<Button
android:id="#+id/submitbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"/>
</FrameLayout>
So here I want to control the submit button in fragment.java. How can I acces the button by findviewbyid or findfragmentbyid. And in fragment.java where do I use that code to access submitbutton.
in OnCreateView
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
button = vv.findViewById(R.id.submitbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return vv;
}
In your QuoteTypeFragment.java
1) Cast the widget by using the view. (view.findViewById()).
2) Set the onClickistener.
3) Implement View.OnClickListener and the onClick method.
public class QuoteTypeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
Button mSubmitButton = vv.findViewById(R.id.submitbutton);
mSubmitButton.setonClickListener(this);
return vv;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submitbutton:
// Control the button
break;
}
}
It is very easy to control button from fragment XML file in the fragment activity.
In your onCreateView use these lines,
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
button = vv.view.findViewById(R.id.submitbutton);
return vv;
}
Related
I'm new to this and i'm doing an app for a university project and I wanted to put a VideoView in my app, so I watched this video ("https://www.youtube.com/watch?v=SrPHLj_q_OQ&t=421s") and did it and worked. But then I add to copy the code from content_main.xml to a fragment and it stopped working and giving an error on the "android:onClick" on the Button. And when I press CTRL+F1 to inspect it says this:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
Heres my xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:background="#003e6f"
android:orientation="vertical"
tools:context=".InicioFragment">
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_gravity="center_horizontal"
android:layout_height="197dp" />
<Button
android:id="#+id/button2"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#FF6600"
android:text="Play"
android:onClick="videoplay"
android:textColor="#ffffff" />
<ImageView
android:id="#+id/imagem2"
android:layout_width="match_parent"
android:layout_height="360dp"
android:layout_alignParentBottom="true"
android:adjustViewBounds="false"
android:background="#drawable/tech3" />
</LinearLayout>
Heres my java:
package intro.android.migueloliveiraapp;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
clk = (Button) findViewById(R.id.button2);
videov = (VideoView) findViewById(R.id.videoView);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Carregar o layout do fragent incial "InicioFragment"
InicioFragment inicioFragment = new InicioFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment, inicioFragment, inicioFragment.getTag())
.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_oliveira) {
Quem_Oliveira quem_oliveiraFragment = new Quem_Oliveira();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
quem_oliveiraFragment, quem_oliveiraFragment.getTag())
.commit();
Toast.makeText(this, "Oliveira", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_profissao) {
Profissao profissaoFragment = new Profissao();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
profissaoFragment, profissaoFragment.getTag())
.commit();
Toast.makeText(this, "Profissão", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_feitos) {
Principais_feitos principais_feitosFragment = new Principais_feitos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
principais_feitosFragment, principais_feitosFragment.getTag())
.commit();
Toast.makeText(this, "Principais Feitos", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_academicas) {
Habilitacoes_Academicas habilitacoes_academicasFragment = new Habilitacoes_Academicas();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
habilitacoes_academicasFragment, habilitacoes_academicasFragment.getTag())
.commit();
Toast.makeText(this, "Habilitações Académicas", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_galeria) {
Galeria galeriaFragment = new Galeria();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
galeriaFragment, galeriaFragment.getTag())
.commit();
Toast.makeText(this, "Galeria", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_contactos) {
Contactos contactosFragment = new Contactos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
contactosFragment, contactosFragment.getTag())
.commit();
Toast.makeText(this, "Contactos", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//video view
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Heres my InicioFragment java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
}
heres my updated InicioFragment.java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.net.Uri;
import android.widget.Button;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
clk = (Button) view.findViewById(R.id.button);
videov = (VideoView) view.findViewById(R.id.videoView);
// bind the views here.
Button button2 = view.findViewById(R.id.button);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
You can use this for click.
Button mPlayVideo;
//In oncreate
mPlayVideo = findViewById(R.id.button2);
mPlayVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
In your xml your tools:context=".InicioFragment refers to your fragment and not your activity.
Your method is found inside the activity and not the fragment class and this is why are getting this error.
You can check Call an activity method from a fragment
But I can recommend using the onClick attribute inside your activities and inside fragment use normal click listener:
View view = findViewById(R.id.viewId);
view .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
This is because you created videoplay() method inside your MainActivity.java . You should put your videoplay() method into the InicioFragment.java as it is the corresponding file for the xml layout you have mentioned above.
Initialize your variables like bellow inside your onCreateView method on InicioFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inicio, container, false);
Button btn1 = view.findViewById(R.id.button_id);
.....
.....
return view;
}
public void videoplay(View v){
.........
.....
}
The following error:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
means that you forget to add the corresponding method in your Activity class when using android:onClick="videoplay" attribute. So, you need to add the following method to your activity:
public void videoplay(View v){
// do something here.
}
The most important part is, android:onClick tag is only working when you're using it inside the content layout of Activity.. So, android:onClick doesn't work when you're using it inside the fragment layout. You need to use the onClickListener instead.
You need to bind the view and add the onClickListener with something like this:
public class InicioFragment extends Fragment {
public InicioFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// bind the views here.
Button button2 = view.findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
}
Pay attention on your xml file that this file's context is your InicioFragment (tools:context=".InicioFragment" )
Therefore, videoplay(View v) should be inside your InicioFragment class.
That's the reason why is not found. It won't search on your MainActivity.
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.testclassfragment, container, false);
Button clk = (Button) view.findViewById(R.id.button);
VideoView videov = (VideoView) view.findViewById(R.id.videoView);
return view;
}
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Since you also have a variable for your button another option is to do:
clk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TESTING", "Clicked");
}
});
I have created an android application using Android Fragments as described in Dynamically Prevent Rotation On Android Fragment.
The application is working fine but the problem is that say a particular fragment say Photo Gallery might calls several http calls and might certain time for bringing all the images. So when we click the Photo Gallery it seems stuck for sometime.
How can we show some slider or progress bar like something till the fragment view get loaded completely?
An example like is as shown below:
My PhotoGalleryFragment is given below
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PhotoGalleryFragment extends Fragment {
public PhotoGalleryFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
// some http calls to be triggered
return rootView;
}
}
You can use ProgressDialog, for example:
public class PhotoGalleryFragment extends Fragment {
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
// some http calls to be triggered
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mProgressDialog = ProgressDialog.show(activity, "", "Loading...", true, false);
}
}
When you http calls are ended you can dismiss the ProgressDialog with mProgressDialog.dismiss().
I'm trying to change the colour of text for my text view within my fragment of my activity but nothing changes because of this error:
Cannot find symbol method findViewById(int)
What can I do to resolve this?
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black">
<TextView
android:id="#+id/WCBank_textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Medium"/>
</RelativeLayout>
Java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TabWCBankTerminus extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_wc_bank_terminus,container,false);
return v;
TextView txt = (TextView)findViewById(R.id.WCBank_textView1);
txt.setText(Html.fromHtml("<font color='#FFD300'>text0</font>" +
"<font color='#00A4A7'> text1</font>" +
"<font color='#E32017'> text2</font>" +
"<font color='#FFFFFF'> text3</font>"
));
}
}
Fragment does not define a findViewById() method, you need to use the View object (v) to call it.
The reasoning behind this is, the Fragment does not know anything about the layout until it's inflated. You're inflating the layout and returning a view object that contains information about the stuff you're trying to configure, so you need to invoke the method on the View object instead of the Fragment.
Change to:
TextView txt = (TextView)v.findViewById(R.id.WCBank_textView1);
Then you return v at the very end of your method, not before you make the configuration changes.
It should look like this when you're done:
public class TabWCBankTerminus extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_wc_bank_terminus,container,false);
TextView txt = (TextView)v.findViewById(R.id.WCBank_textView1);
txt.setText(Html.fromHtml("<font color='#FFD300'>text0</font>" +
"<font color='#00A4A7'> text1</font>" +
"<font color='#E32017'> text2</font>" +
"<font color='#FFFFFF'> text3</font>"
));
return v;
}
}
in your onCreateView you have two errors. First you are return statement has to be, in your case, the last one, otherwise the statements that follow are unreachable. Second you have to invoke findViewById through v. Differently from Activity, Fragment has no findViewById method
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_wc_bank_terminus,container,false);
TextView txt = (TextView)v.findViewById(R.id.WCBank_textView1);
txt.setText(Html.fromHtml("<font color='#FFD300'>text0</font>" +
"<font color='#00A4A7'> text1</font>" +
"<font color='#E32017'> text2</font>" +
"<font color='#FFFFFF'> text3</font>"
));
return v;
}
I have a problem with btn.setOnClickListener(this). I have a simple project that works good, but when I add an action to the button I get the message:
unfortunatelay (app name) has stopped
When I comment btn.setOnClickListener(this) out the project works without any problem.
Here is my code:
package com.example.hello;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static final Context PlaceholderFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements OnClickListener {
Button btn;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
btn=(Button)rootView.findViewById(R.id.Entrer);
btn.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// here is the problem error: no eclosing istance of the type MainActivityis accessible in scope
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
}
My layout is as follows:
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.hello.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:text="#string/hello_world"
android:textSize="16dp" />
<Button
android:id="#+id/Entrer"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:text="Entrer" />
</RelativeLayout>
I dont know if I have simple things that are not go correctly. I'm new to Android programming. Thank you!
btn is null, so when you set onClickListener you get NullPointerException. It's null because it's located in fragment_main.xml, not activity_main.xml. You should move this code from onCreate()
btn = (Button) findViewById(R.id.Entrer);
btn.setOnClickListener(this);
to PlaceholderFragment() as follows:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
btn=(Button) rootView.findViewById(R.id.Entrer);
btn.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
return rootView;
}
}
btn=(Button)findViewById(R.id.Entrer);
btn.setOnClickListener(this);
Most likely, findViewById above is returning null. btn.setOnClickListener is crashing on a null pointer exception. (Because btn is null).
It is extremely likely, since you are using the default fragment structure created by the Eclipse solution, that the Button is really in the fragment layout file (fragment_main.xml) and not in activity_main.xml. (Hence, the button is not in the Activity view, it's in the fragment view).
If that's the case, then move the above two lines into the onCreateView method of the PlaceholderFragment.
My application is divided into fragments, each with its own layout (.xml file).
When I start visualize the first fragment in the onCreate() method of my activity, I set the appropriate layout with setContentView(fragment_first). How do I change, for example, a TextView contained inside the second fragment (fragment_second)?
Generally speaking, a Fragment, or any Activity or View for that matter, should update its own internal UI controls. It's easier, and it's good design. Other classes/events may update the state of the Fragment's data, but it handles how that state is displayed.
Edit to answer commented question:
This is how to load a content view in a Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.pump_info, container, false);
return view;
}
in your onCreateView() method, you should assign all of the views you will need to access later to fields in your fragment class, like this,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
view = inflater.inflate(R.layout.xxx, container, false);
this.aTextView = (TextView)view.findViewById(R.id.a_text_view);
this.anImageView = (ImageView)view.findViewById(R.id.an_image_view);
...
}
you can then use aTextView, etc. at other places in the execution of your fragment.
It seems you set the xml file you intended for your first fragment in your activity.
What you should do in short is create a completely new class and have it extend android.support.v4.app.Fragment, also have your activity extend FragmentActivity instead of just Activity.
Then in your android.support.v4.app.Fragment class (which I shall call your fragment from now on) you should override the onCreateView(LayoutInflater inflate, ViewGroup container, Bundle savedInstanceState){} method and in this method you should put a line like this:
View view = inflater.inflate(R.layout.the_xml_layout_for_this_fragment, container, false); which inflates the layout of the fragment and plants it in the proper place in your activity's layout.
After this your need to return view;, but before you return this view you can do view.findViewById(R.id.id_of_a_view_from_the_xml_layout_file); in order to find an element and manipulate it.
You should create such a fragment class for each fragment you need in your app and have it inflate it's own xml layout file.
For more detailed instructions you can see http://www.youtube.com/watch?v=4BKlST82Dtg or other videos or written tutorials.
EDIT: here is a basic fragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MyFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the view:
View view = inflater.inflate(R.layout.myfrag_layout, container, false);
// manipulate widgets, for example:
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText("read me!!!");
// return the view:
return view;
}
}
and it's parenting activity:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class MyFragmentActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// notice that there is a different layout file for the activity and for
// the fragment!
setContentView(R.layout.xml_layout_for_the_activity);
// to start the fragment and stick it into your activity (not needed if
// you use ViewPager)
FragmentManager fragMan = getSupportFragmentManager();
fragMan.beginTransaction()
.add(R.id.the_visual_element_that_will_contain_your_fragments_layout, fragMan)
.commit();
}
}