Fragment onClick method not working - android

The click listener in my fragment isn't working properly. I'm not getting any debug messages in my logcat whatsoever from my requestData method, nor my onClick method. I was thinking it was probably due to trying to use activity methods from the fragment, but I don't see any problems with doing that; it also wouldn't affect my onClick debug messages not showing up.
Activity:
public class MainActivity extends AppCompatActivity {
public void requestData(String first, String second) {
Log.d(“Success!”, first + “ “ + second);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
}
Fragment:
public class WelcomeFragment extends Fragment implements View.OnClickListener{
private Button mButton;
private EditText mFirstEditText;
private EditText mSecondEditText;
private View v;
public WelcomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mCalculateButton = (Button) v.findViewById(R.id.calculate_button);
mCalculateButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mFirstEditText = (EditText) v.findViewById(R.id.first_editText);
String first = mFirstEditText.getText().toString();
Log.d("Button clicked", "mFirstEditText set " + first);
mSecondEditText = (EditText) v.findViewById(R.id.second_editText);
String second = mSecondEditText.getText().toString();
Log.d("Button clicked", "mSecondEditText set " + second);
v.requestData(first, second);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment
android:id="#+id/welcome_fragment"
android:name="com.example.kent.AnApplication.WelcomeFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
welcome_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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivityFragment">
<TextView
android:text="#string/welcome "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/welcome_textView"
android:textSize="20sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="68dp"/>
<EditText
android:layout_width="280dp"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:id="#+id/first_editText"
android:layout_marginTop="60dp"
android:layout_below="#+id/welcome_textView"
android:layout_centerHorizontal="true"/>
<EditText
android:layout_width="280dp"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:id="#+id/second_editText"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/calculate_button"
android:layout_marginTop="43dp"
android:layout_below="#+id/second_editText"
android:layout_centerHorizontal="true"/>
</RelativeLayout>

You didn't set clicked listener. Try below code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
mButton = (Button) v.findViewById(R.id.your_button_id);
mButton.setOnClickListener(this);
return v;
}
If you have some "clicked" events, you have to use if/else or switch on your onClick(); method.

Change your Fragment code to following:
public class WelcomeFragment extends Fragment implements View.OnClickListener{
private Button mButton;
private EditText mFirstEditText;
private EditText mSecondEditText;
private View v;
public WelcomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
return v;
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mCalculateButton = (Button) view.findViewById(R.id.calculate_button);
mCalculateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v) {
mFirstEditText = (EditText) v.findViewById(R.id.first_editText);
String first = mFirstEditText.getText().toString();
Log.d("Button clicked", "mFirstEditText set " + first);
mSecondEditText = (EditText) v.findViewById(R.id.second_editText);
String second = mSecondEditText.getText().toString();
Log.d("Button clicked", "mSecondEditText set " + second);
v.requestData(first, second);
}
});
}
}

The problem is in your onclick method, you haven't find the id of that Button on which click has occurred, change your onclick() method code as:
#Override
public void onClick(View view) {
if(view.getId() == R.id.calculate_button) {
mFirstEditText = (EditText) v.findViewById(R.id.first_editText);
String first = mFirstEditText.getText().toString();
Log.d("Button clicked", "mFirstEditText set " + first);
mSecondEditText = (EditText) v.findViewById(R.id.second_editText);
String second = mSecondEditText.getText().toString();
Log.d("Button clicked", "mSecondEditText set " + second);
v.requestData(first, second);
}
}
I hope it'll work for you

Related

Android studio EditText doesnt load TextView

Im working in a fragment where I want the user to input an answer and then when clicking a button, a textview should show Correct.
This is my code
public class FragmentOne extends Fragment {
private EditText userAnswer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
final String theAnswer = (userAnswer.getText().toString());
Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (theAnswer.equalsIgnoreCase("Germany")) {
TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
}
}
});
return v;
}
}
However, when Germany is typed, the textView is still just showing 'x' (which I set it to show originally)
Relevant XML's are
<Button
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:id="#+id/submitBtn1"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="220dp"
android:layout_height="70dp"
android:inputType="textPersonName"
android:hint="Write answer and press enter"
android:ems="10"
android:id="#+id/editText"
android:textSize="16sp"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true" />
<TextView
android:text="x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/showCorrect"
android:layout_below="#+id/skipBtn"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp" />
What has gone wrong?
You have to change this line :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
TextView tv = (TextView)v.findViewById(R.id.showCorrect);
Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
tv.setText("Correct!");
}
}
});
return v;
}
i.e : in your code userAnswer value is always the same (not checked on Button click)
Code needed to be changed to:
public class FragmentOne extends Fragment {
private EditText userAnswer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
final TextView tv = (TextView)v.findViewById(R.id.showCorrect); //changed
Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
//TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
}
// updateScore();
}
});
return v;
}

How to replace text of textView in fragment

I want to change a text of TextView on clicking a button. I have 2 buttons in my fragment and both have an onClick method for same TextView. Here is in detail what's happen in my fragment.
I set a default text to TextView means 1st text.
When 1st button clicked the 2nd text will appear on the TextView.
When 2nd button clicked again 1st text will appear on the TextView.
Here is my Fragment code
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d("Rahul", "On Ganpati 1 fragment On Create ");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Rahul", "On Ganpati 1 fragment On Create View ");
// Inflate the layout for this fragment
final TextView textView = (TextView)getView().findViewById(R.id.g1TextView);
textView.setText(getString(R.string.Ganpati_1));
Button marathi = (Button)getView().findViewById(R.id.g1Marathi);
marathi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(getString(R.string.Ganpati_1));
}
});
Button english = (Button)getView().findViewById(R.id.g1English);
english.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(getString(R.string.GanpatiE));
}
});
return inflater.inflate(R.layout.fragment_ganpati_1, container, false);
}
Here is the XML file
<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.lenovo.shopping.Shankar">
<Button
android:layout_width="168dp"
android:layout_height="50dp"
android:text="Left"
android:id="#+id/g1Marathi"
android:textAlignment="center"
android:layout_gravity="left|top" />
<Button
android:layout_width="168dp"
android:layout_height="50dp"
android:text="Right"
android:id="#+id/g1English"
android:textAlignment="center"
android:layout_gravity="right|top" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:paddingBottom="50dp"
android:id="#+id/scrollView"
android:layout_gravity="end|fill_vertical">
<TextView
android:id="#+id/g1TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/TextView" />
</ScrollView>
</FrameLayout>
When use Fragment, you need to override onCreateView and return View like this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ganpati_1, null);
Log.d("Rahul", "On Ganpati 1 fragment On Create View ");
// Inflate the layout for this fragment
final TextView textView = (TextView)view.findViewById(R.id.g1TextView);
textView.setText(getString(R.string.Ganpati_1));
Button marathi = (Button)view.findViewById(R.id.g1Marathi);
marathi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(getString(R.string.Ganpati_1));
}
});
Button english = (Button)view.findViewById(R.id.g1English);
english.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(getString(R.string.GanpatiE));
}
});
return view;
}

how to get text from EditText within a Fragment and not activity

I am trying to get the text from an EditText in an XML I have:`
this is my XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="15dp"
android:text="Name"
android:textColor="#color/accent_red"
android:textSize="25sp" />
<EditText
android:id="#+id/editContactName"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/border"
android:ems="10"
android:hint="Name"
android:imeOptions="actionNext"
android:inputType="textPersonName"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:textSize="30sp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
This is my class classed SHConfigureContactFragment
public class SHConfigureContactFragment extends Fragment{
private EditText name;
private EditText description;
private EditText primaryNumber;
private EditText secondaryNumber;
private EditText email;
private EditText skype;
private Byte[] photo;
private Boolean isDualPane;
private FragmentManager fragmentManager;
private SHContactMenuFragment menuFragment;
private SHConfigureContactFragment contactFragment;
private DatabaseControllerLibrary databaseController;
private Contact contact;
public int selectedIndex;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null) {
this.selectedIndex = savedInstanceState.getInt("SELECTED_INDEX");
this.contact = (Contact) savedInstanceState.getSerializable("CONTACT");
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.sh_fragment_contact_edit, container, false);
return rootView;
}
private void setupTextFieldsByContact(Contact contact) {
name = (EditText) findViewById(R.id.editContactName);
// description = (EditText) findViewById(R.id.editContactDescription);
// primaryNumber = (EditText) findViewById(R.id.editContactPrimaryNumber);
// secondaryNumber = (EditText) findViewById(R.id.editContactSecondaryNumber);
// email = (EditText) findViewById(R.id.editContactEmail);
// skype = (EditText) findViewById(R.id.editContactSkype);
if (contact != null) {
name.setText(contact.getName());
description.setText(contact.getDescription());
primaryNumber.setText(contact.getPrimaryNumber());
secondaryNumber.setText(contact.getSecondaryNumber());
email.setText(contact.getEmail());
skype.setText(contact.getSkype());
}
}
}
It seems as though I cannot callfindViewById(R.id.editContactName)because I am not extending an Activity. I have looked at various posts here but have not found a solution. I thought about using getText() method, but that does not let me get specific EditText elements. I hope to have many editable fields that is why I need to get by the specific ID's
You can access the view inflated in onCreateView(...) by calling getView(). You can use the following code anytime after onCreateView(...):
getView().findViewById(R.id.editContactName)
Here's what I would do inside the fragment:
EditText mName, mDescription, mPrimaryNumber, mSecondaryNumber, mEmail, mSkype;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// no need for super here, the default fragment has no layout
// inflate the layout in this method
View rootView = inflater.inflate(R.layout.sh_fragment_contact_edit, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// save views as variables in this method
// "view" is the one returned from onCreateView
mName = (EditText) view.findViewById(R.id.editContactName);
mDdescription = (EditText) view.findViewById(R.id.editContactDescription);
mPrimaryNumber = (EditText) view.findViewById(R.id.editContactPrimaryNumber);
mSecondaryNumber = (EditText) view.findViewById(R.id.editContactSecondaryNumber);
emEail = (EditText) view.findViewById(R.id.editContactEmail);
mSkype = (EditText) view.findViewById(R.id.editContactSkype);
}
private void setupTextFieldsByContact(Contact contact) {
// call this method anytime the contact changes without having to find views again
if (contact != null) {
mName.setText(contact.getName());
mDescription.setText(contact.getDescription());
mPrimaryNumber.setText(contact.getPrimaryNumber());
mSecondaryNumber.setText(contact.getSecondaryNumber());
mEmail.setText(contact.getEmail());
mSkype.setText(contact.getSkype());
}
}
In the onCreateView method, do this:
name = (EditText) rootView.findViewById(R.id.editContactName);
Hope it will help fix your problem.

Get view for button click on the Fragment of the ViewPager

I have successfully set up the a FragmentActivity with FragementPagerAdapter associated with ViewPager to implement two tabbed application .
One of the Tabs namely "Wave" has a text view and a button . All I want is call textview.setText method via the onClick method of button described by its xml attribute .
I do not know where should I initialize my TextView or Button , how can I get the context of Wave tab and where should I write onclick method-
public class InformationShow extends FragmentActivity {
XMLdata dataObject;
ViewPager viewPager;
PagerAdapter adpt;
Fragment temp;
TextView tv;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewPager=(ViewPager)findViewById(R.id.pager);
adpt = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adpt);
// temp=adpt.fg.findFragmentById((int)adpt.getItemId(1));
tv=(TextView)findViewById(R.id.graphWaveTextView);
bt = (Button)findViewById(R.id.button1);
}
public void changeText(View v){
tv.setText("It worked ");
}
Adapter Class
public class PagerAdapter extends FragmentPagerAdapter {
int count = 2;
CharSequence namme[] = {"Temperature","Wave"};
XMLdata data;
FragmentManager fg;
public PagerAdapter(FragmentManager fragmentManager ){
super(fragmentManager);
this.fg = fragmentManager;
}
Context context;
#Override
public Fragment getItem(int arg0) {
switch (arg0){
case 0:{
TemperatureGraphFrag temp = new TemperatureGraphFrag();
return temp;
}
case 1:{WaveHeightGraphFrag wave = new WaveHeightGraphFrag();
return wave;
}
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return namme[position];
}
}
Fragments Class
public class TemperatureGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_t, container, false);
return view;
}
}
public class WaveHeightGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_sig_wave_height, container, false);
return view;
}
}
fragment_main XML implemented by FragmentActicity
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#65C2C9"
android:scrollbarSize="5dp"/>
</android.support.v4.view.ViewPager>
Tab 2 Fragment XML graph_sig_wave_height
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/graphWaveTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_gravity="center"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center"
android:onClick="changeText"/>
</LinearLayout>
Tab 1 fragment layout XML graph_t
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linearTemp"
>
<TextView
android:id="#+id/graphTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_gravity="center"
/>
</LinearLayout>
Add the following method to your WaveHeightGraphFrag class:
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
final TextView t = (TextView) view.findViewById(R.id.graphWaveTextView);
Button b = (Button) view.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
t.setText("It worked ");
}
});
}
This is what you want.

How to inflate view inside fragment

If I try to inflate a view within a fragment I am getting NULL.. For example:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Here I will inflate my view using the layout ID & return.
return view;
}
Whenever a button is clicked I need to create a dynamic view e.g.: button & add to the LinearLayout. I would like to perform this operation inside my fragment class like this:
public void addPlaces() {
Button button = new Button(null);
button.setText("button name");
// e.g. like adding button to enter code here linear layout
linearLayout.addView(button);
}
So, if I get inflate LinearLayout inside onCreateView and use it in add class, I'm getting NULL. How to achieve?
Declare the variable as a instance variable and then initialize Linear Layout
LinearLayout linearLayout;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
return rootView;
}
Then
public void addPlaces() {
Button button = new Button(getActivity());
// needs activity context
// fragment hosted by a activity. use getActivity() to get the context of the hosting activity.
button.setText("button name");
linearlayout.addView(button);
}
Example: Modify the below according to your requirement.
fragment1.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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<LinearLayout
android:layout_width="fill_parent"
android:id="#+id/linearlayout"
android:layout_height="fill_parent"
android:layout_above="#+id/button1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
Myfragment.java
public class Myfragment extends Fragment {
LinearLayout linearLayout;
View rootView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPlaces();
}
});
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
public void addPlaces() {
Button button = new Button(getActivity()); // needs activity context
button.setText("button name");
linearLayout.addView(button);
}
}
Snap shot of my emulator
Edit :
activity-main.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"
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=".MainActivity" >
<fragment android:name="com.example.fragments.Myfragment"
android:id="#+id/frag"
android:layout_above="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends FragmentActivity {
Button b;
Myfragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment = new Myfragment();
fragmentTransaction.add(R.id.frag, fragment);
fragmentTransaction.commit();
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fragment.addPlaces();
}
});
}
}
Myfragment.java
public class Myfragment extends Fragment {
LinearLayout linearLayout;
View rootView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
public void addPlaces() {
Button button = new Button(getActivity()); // needs activity context
button.setText("button name");
linearLayout.addView(button);
}
}

Categories

Resources