Android Programming - Fragments and Listeners - android

I am following a tutorial on the internet and I have to make a listener for my buttons. The tutorial I am watching is very different from my code even though the video was posted not even a year ago. The video I am watching has no "fragment" code in it. In my code there is a fragment in my MainActivity.java. What is a fragment? In my mainactivity.java towards the end I get this:
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);
button1 = (Button)rootView.findViewById(R.id.button1);
button2 = (Button)rootView.findViewById(R.id.button2);
button3 = (Button)rootView.findViewById(R.id.button3);
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
return rootView;
}
}
could anyone explain to me what a place holder fragment is? heres my code. I am getting an error here:
ERROR: "Toast.makeText(MainActivity.this, "toast", Toast.LENGTH_SHORT);"
Message: "No enclosing instance of the type MainActivity is accessible in scope"
.
private static OnClickListener listener = new OnClickListener()
{
#Override
public void onClick(View v) {
int id = v.getId();
switch(id)
{
case R.id.button1:
Toast.makeText(MainActivity.this, "toast", Toast.LENGTH_SHORT);
break;
case R.id.button2:
break;
case R.id.button3:
break;
default:
break;
}
}
};
HERES MY FULL CODE ( MainActivity.java ):
package com.example.androiddevelopmentonline_part2_1;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
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;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
private static Button button1, button2, button3;
#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);
}
private static OnClickListener listener = new OnClickListener()
{
#Override
public void onClick(View v) {
int id = v.getId();
switch(id)
{
case R.id.button1:
Toast.makeText(MainActivity.this, "toast", Toast.LENGTH_SHORT);
break;
case R.id.button2:
break;
case R.id.button3:
break;
default:
break;
}
}
};
/**
* A placeholder fragment containing a simple view.
*/
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);
button1 = (Button)rootView.findViewById(R.id.button1);
button2 = (Button)rootView.findViewById(R.id.button2);
button3 = (Button)rootView.findViewById(R.id.button3);
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
return rootView;
}
}
}

Probably the best explanation is in the Developer Docs (here: https://developer.android.com/guide/components/fragments.html)
Here's something from the "QuickView"
Fragments decompose application functionality and UI into reusable modules
Add multiple fragments to a screen to avoid switching activities
Fragments have their own lifecycle, state, and back stack
Fragments require API Level 11 or greater
The way I paraphrase it, is that its a reusable component of the UI with it's own lifecycle. It is used to decompose your UI into (multiple), more self contained, and logical "sections".
In your case, I think your IDE has auto generated the code for you and generated the PlaceholderFragment. It is as it says, an autogenerated placeholder. You can get rid of it if you're only working with Activities for now. But its best to look up Fragment tutorials later as they are used quite frequently with newer versions of android (Fragments are not necessary, but they're sorta 'better practice', depending on your application architecture).
The reason you're getting an error with:
ERROR: "Toast.makeText(MainActivity.this, "toast", Toast.LENGTH_SHORT);"
Message: "No enclosing instance of the type MainActivity is accessible in scope"
is actually explained in the message. You've declared your OnClickListener into an anonymous, static, attribute. Because it is static, it cannot access the current instance of the class (it is "not in scope", it has no access to the non-static methods and attributes). To fix it, just remove the static keyword:
private OnClickListener listener = new OnClickListener() //... etc
For an explanation about the static keyword in Java, look here: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html or What does the 'static' keyword do in a class?
EDIT (A neater way of implementing OnClickListener)
A better idea would be to put your OnClickListener within your PlaceholderFragment (since that's where it's used), or have your PlaceholderFragment implement View.OnClickListener (I prefer this way, less anonymous types, it code formats better, but its a matter of preference). An example (look for the comments):
// note, doesn't matter if it is static
// I got rid of the OnClickListener attribute and made PlaceholderFragment implement OnClickListener like so
public static class PlaceholderFragment extends Fragment implements OnClickListener
{
// No need to provide a constructor. Fragments by default should have an empty constructor. If you want to add data to it, you need to create a "newInstance" method which calls fragment.setArguments (SomeBundleWithValuesInIt)
# Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate (R.layout.fragment_main, container, false);
button1 = (Button) rootView.findViewById (R.id.button1);
button2 = (Button) rootView.findViewById (R.id.button2);
button3 = (Button) rootView.findViewById (R.id.button3);
// I set the OnClickListener to the PlaceholderFragment itself, because it implements OnClickListener (which is an interface), you can use it this way.
button1.setOnClickListener (this);
button2.setOnClickListener (this);
button3.setOnClickListener (this);
return rootView;
}
// OnClickListener.onClick(View) moved here.
# Override
public void onClick(View v)
{
int id = v.getId ();
switch (id) {
case R.id.button1 :
// getActivity() can be used instead of Context (Activity is one of the subclasses of Context), but only within a Fragment in this case
Toast.makeText (getActivity (), "toast", Toast.LENGTH_SHORT);
break;
case R.id.button2 :
break;
case R.id.button3 :
break;
default :
break;
}
}
}

Related

how to add bottom navigation bar in another fragment

I have already add an bottom navigation bar into my project with 3 fragments (Home_fragment, Wallet_fragment,Account_fragment). I have added login button in Account_fragment. Now i want that When ever i click on login button login_fragment(afterlogin_fragment) open with bottom navigation bar.
I have attaching a link to video showing my problem. link -- https://cloud.degoo.com/share/o41Axz4FYFHBx7
and here is codes ---
mainActivity ---
BottomNavigationView bottomNavigationView = findViewById(R.id.main_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_layout, new HomeFragment()).commit();
}
BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selecrFlag = null;
switch (menuItem.getItemId())
{
case R.id.nav_home:
selecrFlag = new HomeFragment();
break;
case R.id.nav_wallet:
selecrFlag = new WalletFragment();
break;
case R.id.nav_Account:
selecrFlag = new AccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_layout, selecrFlag).commit();
return true;
}
};
};
Account_fragment ---
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_account, container, false);
EmailID = v.findViewById(R.id.editTextEmail);
Passwd = v.findViewById(R.id.editPassword);
SignUpBt = v.findViewById(R.id.signbutton);
LoginBt = v.findViewById(R.id.loginbutton);
LoginBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(AccountFragment.this.getContext(),AfterLogin.class));
}
});
afterlogin Fragment --
package com.thechamp.earnbyads;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class AfterLogin extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
}
}
Look like you are confused. the way that you move to another Screen is not Fragment. It is Activity.
There are many ways to deal with this.
you can change your AfterLogin to Fragment.
or implement the AfterLogin Activity as what you implement in your Current Activity that has those 3 Fragments.

One Fragment inside ViewPager doesn't show up

I have a Tabbed Activity hosting a viewpager (auto-generated with eclipse wizard). I slightly modified just the auto generated FragmentPagerAdapter in order to instantiate a specific fragment on each tab. Initially i had 4 tab, 3 fragments for the first tabs and still the auto generated placeholder in the last one, and they worked. When i replaced the last placeholder with an instance of one of my Fragment i faced the following problem: the fragment in one of the last two tabs stays blank, as follow:
_____1st TAB___|____2nd TAB_|___3rd TAB_____|____4th TAB____|
[MasterFragment][RequestMap][MasterFragment][MasterFragment]
This stays blank_____________________|
Moreover, if i make a "random" sequence of actions (change tabs, click on the buttons to perform some actions,...) the fragment that doesn't show up swaps, and becomes the last one as follow:
_____1st TAB___|____2nd TAB_|___3rd TAB_____|____4th TAB____|
[MasterFragment][RequestMap][MasterFragment][MasterFragment]
This stays blank__________________________________|
Here's the code for my FragmentPagerAdapter:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case REQUEST_TAB:
masterFragment = new MasterFragment(MasterFragment.ALL_REQUEST);
return masterFragment;
case MAP_TAB:
requestMap = new RequestMap();
return requestMap;
case OWNER_TAB:
masterFragmentOwner = new MasterFragment(MasterFragment.OWNER_REQUEST);
System.out.println("I should have created the Owner MasterFragment");
return masterFragmentOwner;
case JOINED_TAB:
masterFragmentJoined = new MasterFragment(MasterFragment.JOINED_REQUEST);
return masterFragmentJoined;
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case REQUEST_TAB:
return getString(R.string.request_tab_title).toUpperCase(l);
case MAP_TAB:
return getString(R.string.map_tab_title).toUpperCase(l);
case OWNER_TAB:
return getString(R.string.owner_tab_title).toUpperCase(l);
case JOINED_TAB:
return getString(R.string.joined_tab_title).toUpperCase(l);
default:
return "";
}
}
}
I omit the code regarding the setup of the viewPager because is the same auto generated from the eclipse wizard. While here's the code for the MasterFragment class:
package it.polimi.frontend.fragment;
import it.polimi.appengine.entity.manager.model.Request;
import it.polimi.appengine.entity.manager.model.User;
import it.polimi.frontend.activity.R;
import it.polimi.frontend.util.QueryManager;
import it.polimi.frontend.util.QueryManager.OnRequestLoadedListener;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MasterFragment extends Fragment implements OnRequestLoadedListener, RequestList.OnRequestSelectedListener, RequestDetail.OnUserClickedListener{
private boolean twoPane;
private static View view;
public final static int ALL_REQUEST=0;
public final static int OWNER_REQUEST=1;
public final static int JOINED_REQUEST=2;
private int mode;
public MasterFragment(){
this.mode=0;
}
public MasterFragment(int mode){
this.mode=mode;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
QueryManager.getInstance().addListener(this);
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.fragment_master,container, false);
List<Request> requests = new ArrayList<Request>();
RequestList requestListFragment = null;
switch (mode) {
case OWNER_REQUEST:
requests = QueryManager.getInstance().getCurrentUser().getRequests();
System.out.println("Dovrei aver recuperato le richieste dell'owner");
break;
case JOINED_REQUEST:
String mail=null;
if (QueryManager.getInstance().getCurrentUser()!=null){
User current =QueryManager.getInstance().getCurrentUser();
mail = current.getPwAccount() != null ?
current.getPwAccount()
: current.getGmailAccount() != null ?
current.getGmailAccount()
: current.getFbAccount() != null ?
current.getFbAccount()
: null;
requests = QueryManager.getInstance().getUserPartecipation(mail);
}
else
requests = new ArrayList<Request>();
break;
default: //ALL_REQUEST case and all the other possibilities
requests = QueryManager.getInstance().getRequests();
break;
}
requestListFragment = new RequestList(requests, mode);
if (view.findViewById(R.id.detail_container) != null) {//TABLET CASE
twoPane = true;
getChildFragmentManager().beginTransaction()
.replace(R.id.request_list_container,requestListFragment,RequestList.ID)
.commit();
} else { //PHONE CASE:
getChildFragmentManager().beginTransaction()
.replace(R.id.container,requestListFragment,RequestList.ID)
.commit();
}
} catch (InflateException e) {
// is already there, just return view as it is
e.printStackTrace();
}
return view;
}
#Override
public void onRequestSelected(int position, Request request) {
if (twoPane) {
DetailContainerFragment detailContFrag = new DetailContainerFragment(request,mode);
getChildFragmentManager().beginTransaction()
.replace(R.id.detail_container, detailContFrag, DetailContainerFragment.ID).commit();
} else {
switch (mode) {//This empty switch if for future changes
case OWNER_REQUEST:
break;
case JOINED_REQUEST:
break;
default://ALL_REQUEST
break;
}
RequestDetail fragment = new RequestDetail(request,mode);
Fragment reqList=getChildFragmentManager().findFragmentByTag(RequestList.ID);
getChildFragmentManager().beginTransaction()
.hide(reqList)
.addToBackStack(RequestDetail.ID)
.add(R.id.container,fragment,RequestDetail.ID)
.commit();
}
}
#Override
public void onUserClicked(User user,String requestId) {
if (!twoPane) {
FeedbackDetail fragment = new FeedbackDetail(user,this.mode,requestId);
Fragment reqDetail=getChildFragmentManager().findFragmentByTag(RequestDetail.ID);
getChildFragmentManager().beginTransaction()
.hide(reqDetail)
.addToBackStack(FeedbackDetail.ID)
.add(R.id.container,fragment,FeedbackDetail.ID)
.commit();
} else {
/*DetailContainerFragment should take care of it*/
}
}
#Override
public void onRequestLoaded(List<Request> requests) {
System.out.println("Ho caricato: "+requests.size());
RequestList requestListFragment = (RequestList)getChildFragmentManager().findFragmentByTag(RequestList.ID);
switch (mode) {//Also this switch is for future changes, but the requests list is anyway fetched and assigned to RequestList above
case OWNER_REQUEST:
//TODO
break;
case JOINED_REQUEST:
//TODO
break;
default: //ALL_REQUEST
if (requestListFragment!=null)
requestListFragment.setRequestAdapter(requests);
break;
}
}
}
If i'm missing something important please, let me know.
Thank you all in advance
EDIT:
I forgot to say that the System.out that i placed show up in the console, so the "blank" fragment should have been created, and it should have passed through his onCreateView().
I found the bug. The problem was
private static View view;
because of the static properties. Removing "static" it worked again. Actually i can't explain even now how it could have worked for a while on the first and last tabs and not in the third, because the static attributes should be shared among all instances of the class. Because of the internals of the ViewPager the problem seemed to show up only on adjacent identical MasterFragment, if they where interleaved with any other fragment it worked.

Getting value from Fragment into mainActivity

I have a MainActivity. It's layout contains a fragmentContainer and an actionBar. Then I have 2 different fragments containing various EditTexts.All of them have Ids. I populate the fragmentContainer with the fragments when user clicks a button in actionBar. Everything works perfectly.
Now...the app, is supposed to collect the contents of all EditTexts from both fragments when I push a button (in the menu of the actionBar). But it does not work. It crashes when I try to access the EditTexts directly from the activity. I understand that I should create a public method inside the code of the fragments that will return the values I am interested in. But I seem to be doing something wrong because the method is not accessible from the main (TabActivity)
Here is my code:
public class TabActivity extends Activity {
ActionBar.Tab tab_alocare, tab_merc;
Fragment fragmentTab1 = new aloc_fragment();
Fragment fragmentTab2 = new merc_fragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab); // this layout contains the fragmentContainer
...// here I do some actionBar stuff
}
...
}
An example of one of the fragments is bellow:
public class aloc_fragment extends Fragment {
EditText mEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_aloc, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mEditText = (EditText) getView().findViewById(R.id.edaloc);
}
public String getMyText() {
String rez = "";
if (mEditText.getText()!=null) {
rez = mEditText.getText().toString();
}
return rez;
}
}
Now... if inside the Activity code I want to access the edaloc EditText using findViewById, it crashes the app with nullException. So I then tried to access the public method of the fragment so that it would return me the value that I need. But "getMyText" method is not accessible from the TabActivity.
So, this code does not work:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
Fragment alocfragment = (Fragment) getFragmentManager().findFragmentByTag("aloc");
String s = alocfragment.getMyText(); // this is not compiling at all
I am clearly doing something wrong.
Please advise.
Thank you
There are lots of mistakes in your code, You have neither declared nor initialize the fragments at proper place. Also, you are trying to create another instance of fragment in onOptionsItemSelected which is wrong, you need to use same instance of fragment there to access your functions with values. I hope you know how to add and inflate fragment. See my comments and code changes.
Try with this -
public class TabActivity extends Activity {
ActionBar.Tab tab_alocare, tab_merc;
//Declare fragments here
Fragment fragmentTab1;
Fragment fragmentTab2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab); // this layout contains the fragmentContainer
//Initialize here
fragmentTab1 = new aloc_fragment();
fragmentTab2 = new merc_fragment();
//inflate/add fragments here to the activity
...// here do your actionBar stuff
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
//Now, use same instance of fragment to access your function
String s = fragmentTab1.getMyText();
}
}
public class aloc_fragment extends Fragment {
EditText mEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_aloc,
container, false);
//hold edittext here in the variable
mEditText = (EditText) view.findViewById(R.id.edaloc);
return view;
}
public String getMyText() {
String rez = "";
if (mEditText.getText()!=null) {
rez = mEditText.getText().toString();
}
return rez;
}
}
Also, must to go through Fragment tutorial on Android Developer Fragment Link Link 2, Using Fragments

Fragment implements OnClickListener

I've got an application that I'm modernizing. One step of this process is changing to a Fragment based layout (using the Fragments from the support library).
I converted my Activities into Fragments, and got the layout working nicely (using a ViewPager, cool stuff!)
I was having my Activities implement OnClickListener for all of my button-pressing needs. I have the new Fragment incarnations doing the same thing of course, but it looks like "onClick" is never getting hit. Is there something special about Fragments that prevents them from working this way?
Just do one this
public class fragmentOne extends Fragment implements OnClickListener {
Button myButton;
#Override
public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
View myView = inflater.inflate(R.layout.fragment_1, container, false);
myButton = (Button) myView.findViewById(R.id.myButton);
myButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View v) {
// implements your things
}
}
very simple
I will Focus to use the OnClick action for global access, You have to do like this is your project, Must Implement the View.OnClickListener, then Override the Method
OnClick(), In OnCreateView() have to do like this button_submit.setOnClickListener(this); for the Views you need,
Please see the below code for Clear Answer,Thankyou.
public class New_Project extends Fragment implements View.OnClickListener{
private View mView;
private Button button_submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_newproject, container,false);
button_submit=(Button)mView.findViewById(R.id.button_submit);
button_submit.setOnClickListener(this);
return mView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_submit:
//do your stuff
break;
}
}
}
I want to comment on Abhijit Chakra answer but it seems that I need to have 50 reps for that. For those who are wondering if you can't use Abhijit's answer, it is because of:
public void OnClick(View v) {
// implements your things
}
You need to make sure that it is onClick, NOT OnClick. Thankfully Android Studio internal error message come to rescue.
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.imgView1:
Toast.makeText(getActivity(), "Long pressing", Toast.LENGTH_SHORT).show();
updateImage();
break;
case R.id.imgView2:
Toast.makeText(getActivity(), "Long pressing", Toast.LENGTH_SHORT).show();
updateImage();
break;
case R.id.imgView3:
Toast.makeText(getActivity(), "Long pressing", Toast.LENGTH_SHORT).show();
updateImage();
break;
default:
break;
}

onClick inside fragment called on Activity

i am encapsulating stuff into a fragment at the moment and run into a problem that is hard to google.
Inside my fragment are some buttons with onClick attributes but they are called on the Activity rather the fragment from the android system - this makes encapsulating a bit clumsy. Is there a way to have the reflection stuff from onClick to call on the fragment? The only solution to this I see at the moment is not to use onClick in the xml and set click-listeners inside the fragment via code.
I spoke to some googlers # #adl2011 - they recognize the problem and perhaps there will be a fix of that in the future. Until then - one should use .setOnClick in the Fragment.
The problem is that when layout's are inflated it is still the hosting Activity that is receiving the button clicks, not the individual Fragments.
I prefer using the following solution for handling onClick events. This works for Activity and Fragments as well.
public class StartFragment extends Fragment implements OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_start, container, false);
Button b = (Button) v.findViewById(R.id.StartButton);
b.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StartButton:
...
break;
}
}
}
Then problem is gone.
It works for me
Add import:
import android.view.View.OnClickListener;
Fragment.java
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = (ViewGroup) inflater.inflate(R.layout.fragment, container, false);
Button mButton = (Button) rootView.findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return rootView;
}
ISSUE:
1.In XML onClick attribute will call activity's public method.
2.Fragment's public method not called.
3.Fragment reusability.
SOLUTION:
In Fragment's layout add this to the View.
android:onClick="onFragmentViewClick"
In each activity the fragment may belong..
public void onFragmentViewClick(View v) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (fragment != null && fragment.isVisible()) {
if (fragment instanceof SomeFragment) {
((SomeFragment) fragment).onViewClicked(v);
}
}
}
In the Fragment include this method..
public void onViewClicked(View v) {
switch (v.getId()) {
case R.id.view_id:
Log.e("onViewClicked", "yehhh!!");
break;
}
}
You could have the listener that is being called in the activity forward the call onto a listener in the fragment. You should have a reference to the fragment inside of the FragmentActivity to pass the call on. You will have to cast to call the method or have your fragment implement an interface you define. I know that isn't the best solution but it will work. You could also use the tag of a button to specify the method name to call if you wanted. Hope this helps a bit.
Try this...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_ipadditional_users, container, false);
FloatingActionButton button7 = (FloatingActionButton) rootView.findViewById(R.id.fab_ip_additional_user);
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), IPAdditionalUsersEdit.class);
startActivity(intent);
}
});
return rootView;

Categories

Resources