2

I have a FragmentActivity in which a Fragment is attached. Now at a particular step in onBackPressed of the Fragment Activity, I want to change the DRAWABLE OF A BUTTON which is defined in Fragment and not in the Fragment Activity.

My Question is: How can I change the drawable of that Button (which is defined under Fragment), in my Fragment Activity's onBackPressed Method.

Thanks

Illegal Argument
  • 10,090
  • 2
  • 44
  • 61
Gaurav Arora
  • 8,282
  • 21
  • 88
  • 143
  • @Nachi What the hell ?? Have you read the Question Carefully ???? What I am asking is how to find the view of Fragment in the FragmentActivity. It is not about the Backpressed, – Gaurav Arora Oct 28 '14 at 09:44
  • Take a closer look at this answer: http://stackoverflow.com/a/19133522/1025599. You need to define an interface in your fragment that can be called from the parent activity. Inside the fragment you can get a reference to your view and change the drawable there. – Nachi Oct 28 '14 at 09:47
  • @Gaurav check my explanation..Hope it helps – Chiradeep Oct 28 '14 at 09:47

3 Answers3

2

While you click back, then onBackPress Method of your attached activity will be called.

Now if you want to manipulate something in Fragment class create an Interface.

Follow this way :->

Step 1:

   Activity onBackPress(){
   myinterface.changebutton()
    }

Step 2:

 public Interface myinterface{
 public void changeButton(){}
 }

Step 3:

  Fragment class implements myinterface{

  onCreateView{
  // Intialize the Button view here}

  public void changeButton(){

  mybutton.setBackgroundResource();
  }
Chiradeep
  • 973
  • 12
  • 32
0

Let me assume that the fragment is LoginFragment having a button(public scope) loginButton. Then you can do something like this in your onBackPressed:

LoginFragment fragment = new LoginFragment();// this is a class level variable 
// on in back pressed
fragment.loginButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher) );

Alternately you can have a method on your LoginFragment to change the backgroundDrawable:

public void changeBackGround(){
    loginButton.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.ic_launcher)
}
// call it like this
fragment.changeBackGround();
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61
0

I would do it like this:

       ((Button)fragment.getView().findViewById(R.id.yourButtonId)).setBackground(getResources().getDrawable(R.drawable.your_drawable_id));
okkko
  • 1,010
  • 1
  • 13
  • 22