update TextView in fragment A when clicking button in fragment B

前端 未结 2 554
北海茫月
北海茫月 2020-12-22 07:02

I have two fragments sitting side by side in the same activity. When I touch a button in the right fragment (fragment B), I need a TextView in the left fragment to update (f

相关标签:
2条回答
  • 2020-12-22 07:23

    One fragment should not communicate to another fragment directly. It should do so through attached activity. The detail explanation with code example is available here

    Android Developer site

    Declare an interface in Fragment B, and implement the interface in the activity. Call the interface through callback in Fragment B when button is clicked. You can have a public function in Fragment A to update the TextView, so activity directly call the function to update the text.

    0 讨论(0)
  • 2020-12-22 07:36

    You can define an interface in Fragment B and implement it on the MainActivity. Then on the callback method (onClickOnB in this case) set the text on the TextView. You should obtain a reference of the TextView in the Activity's onCreate() after setContentView(). This works because Fragment A is static. Otherwise, you can create a public method inside Fragment A so you can set the text from inside the callback by getting a reference of Fragment A and calling such method.

    Fragment B

    public class FragmentB extends Fragment implements onClickListener{
    ClickOnB listener;
    public void setOnFragmentBClickListener(ClickOnB listener){
    this.listener = listener;
    
    }
    
    @Override
    
    public void onClick(View v){
    //stringMessage is a `String` you will pass to `Fragment` A to update its `TextView`
    listener.onClickOnB(stringMessage);
    }
    
    interface ClickOnB{
    public void onClickOnB(String message);
    }
    
    }
    

    MainActivity

    public class MainActivity extends Activity implements ClickOnB{
    @Override   
    protected onCreate(Bundle savedInstanceState){
    
    //Get a reference of `Fragment` B somewhere in your code after you added it dynamically and set the listener.
    ((FragmentB)getFragmentManager().findFragmentByTag("FragmentB")).setOnFragmentBClickListener(this);
    
    }
    
    @Override
    public void onClickOnB(String message){
    
    //Set the text to the `TextView` here (I am assuming you get a reference of the `TextView` in onCreate() after inflating your layout.
    
    mTextView.setText(message);
    
    }
    }
    
    0 讨论(0)
提交回复
热议问题