在MainActivity中的A片段和B片段之间进行通信

时间:2014-09-25 00:41:14

标签: android fragment communication android-fragmentactivity

我在这些工作上挣扎

  1. 问题

      

    在片段和B片段之间,当A片段发生点击事件时,如何设置B片段的视图

  2. IDE:Android Studio

  3. TargetFragments A. NavigationDrawer Fragment

    • For Left NavigationDrawer Menu ..

    B中。占位符片段

    • 在NavigationDrawer上发生点击事件
    • ,在FrameLayout上设置TextView(来自MainActivity)
  4. 我想要什么

    • 点击事件发生在片段(导航抽屉)时,
    • 我想从另一个片段(PlaceholderFragment)
    • 设置Textview
    • 在MainActivity'布局
    • 上绑定到FrameLayout
  5. 我做了什么:

    1)在回调(来自导航抽屉片段)中,获取PlaceholderFragment' s 的TextView(section_label)

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
    
       FragmentManager fragmentManager = getFragmentManager();
       fragmentManager.beginTransaction()
            .replace(R.id.container, PlaceholderFragment.newInstance(position + 1), "MY_FRAGMENT"+(position + 1))
            .commit();        
    
    Log.d("INFO","MY_FRAGMENT"+(position + 1));
    
       TextView LabelText  = (TextView)findViewById(R.id.section_label);
       LabelText.setText("Its works i think");
      // 클릭 이벤트가 발생했을경우 내용을 가져와서 별도 처리하는 부분 ....
    
    Toast.makeText(MyActivity.this, "HelloWorld", Toast.LENGTH_SHORT).show();
    
    }  
    

    2)onCreate,获取ViewText,设置

     @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    
    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();
    
    
    Log.d("INFO","OnCreate진입");
    //RelativeLayout some = (RelativeLayout)findViewById(R.layout.fragment_my);
    
     TextView LabelText  = (TextView)findViewById(R.id.section_label);
     LabelText.setText("Its works i think");
    
    
    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
    
    
    }
    
  6. 结果

    • 所有他们返回" Null"

1 个答案:

答案 0 :(得分:0)

在您的片段中,定义一个接口并为其提供一个发送数据的方法:

public interface Communicator{
    public void sendData(String data);
}

然后,在您的活动中,实施您的界面

...MyActivity implements Communicator{

实例化您的FragmentB:

FragmentB fb = new FragmentB();

覆盖方法:

public void sendData(String data){
    //Do something with data
    fb.changeData(data);
}

在FragmentB中,定义一个名为changeData的方法:

public void changeData(String data){
    textview.setText(data);
}