update TextView in fragment A when clicking button in fragment B

前端 未结 2 646
北海茫月
北海茫月 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: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);
    
    }
    }
    

提交回复
热议问题