Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the fragment's button in an activity

i am creating two java file 1st main activity.java file 2nd fragment.java file create button on fragment.java how to click listener written on activity.java help me

fragment.java

public class fragment extends fragment{
Button btn;
// some code
btn = (Button)layout.findviewbyid(R.id.btn1);

}

}

activity.java

public class activity extends Activity
{


 // how to access the click action btn here
 btn.setOnclicklistner(new View.OnClickLisitner(){
 public OnClick(){


 }
like image 492
Jai Avatar asked Jan 09 '15 12:01

Jai


Video Answer


2 Answers

To use the button in activity from the fragment, you have to use getActivity()

In your fragment,

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_item_select, container, false);

        btn = (Button) getActivity().findViewById(R.id.btn);
}

btn is the button in activity

getActivity() in a Fragment returns the Activity the Fragment is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).

like image 158
reverie_ss Avatar answered Sep 19 '22 03:09

reverie_ss


You can define custom clickListener class and create it's instance in fragment and set listener instance there. Now you can write code in that class. Hope it will help you.

public class MyCustomListener implements OnClickListener{

     @override
     public void onClick(View v){

     // you stuff
     }  
}

then in your fragment call this

MyCustomListener listener=new MyCustomListener();
btn.setOnClickListener(listener);
like image 32
SAM Avatar answered Sep 21 '22 03:09

SAM