How to send data from an Activity to a Fragment?

1

As you can see in the code below I can send data from one Fragment to another and also from a Fragment to Activity but I have tried everything to send from Activity to Fragment but I can not:

MainActivity.java

public class MainActivity extends AppCompatActivity {

String TabFragmentB;
String TabFragmentA;

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new OneFragment(), "One");
    adapter.addFrag(new TwoFragment(), "Two");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

////Métodos que se relacionam com os fragments para trasporte de dados////

//Captura a Tag do fragment OneFragment
public void setTabFragmentA(String t){
    TabFragmentA = t;
}

//Retorna a Tag do fragment OneFragment
public String getTabFragmentA(){
    return TabFragmentA;
}


//Captura a Tag do fragment TwoFragment
public void setTabFragmentB(String t){
    TabFragmentB = t;
}

//Retorna a Tag do fragment TwoFragment
public String getTabFragmentB(){
    return TabFragmentB;
}

//Envia dados para o fragment OneFragment
public void msg_fragA(String message){

}

}

OneFragment.java

public class OneFragment extends Fragment {

static TextView statusMessage;
static TextView txt_temporizador;
static TextView txt_limite;
static TextView txt_espera;
static TextView txt_clock;

public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Infla o layout do fragment
    View myFragmentView = inflater.inflate(R.layout.fragment_one, container, false);

    String myTag = getTag();//Grava a Tag do fragment
    ((MainActivity) getActivity()).setTabFragmentA(myTag);//Grava a Tag do fragment em uma váriavel da MainActivity

    statusMessage = (TextView) myFragmentView.findViewById(R.id.statusMessage);
    txt_temporizador = (TextView) myFragmentView.findViewById(R.id.txt_temporizador);
    txt_limite = (TextView) myFragmentView.findViewById(R.id.txt_limite);
    txt_espera = (TextView) myFragmentView.findViewById(R.id.txt_espera);
    txt_clock = (TextView) myFragmentView.findViewById(R.id.txt_clock);

    return myFragmentView;
}

public void dados_update(String tp, String tl, String te, String cl) {
    //Esse metódo recebe dados do TwoFragment ao ser apertado o botão envia do mesmo

    txt_temporizador.setText(tp);
    txt_limite.setText(tl);
    txt_espera.setText(te);
    txt_clock.setText(cl);

}


}

TwoFragment.java

public class TwoFragment extends Fragment {

Button btn_envia;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Infla o layout do fragment
    View myFragmentView = inflater.inflate(R.layout.fragment_two, container, false);

    String myTag = getTag();//Grava a Tag do fragment
    ((MainActivity) getActivity()).setTabFragmentB(myTag);//Grava a Tag do fragment em uma váriavel da MainActivity

    btn_envia = (Button) myFragmentView.findViewById(R.id.button_enviar);
    btn_envia.setOnClickListener(Envia_dados);

    return myFragmentView;
}

//Instruções que serão seguidas quando o botão enviar for clicado
View.OnClickListener Envia_dados
        = new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {

        String TabOfFragmentA = ((MainActivity) getActivity()).getTabFragmentA();//Captura a Tag do fragment OneFragment

        OneFragment fragmentA = (OneFragment) getActivity()
                .getSupportFragmentManager()
                .findFragmentByTag(TabOfFragmentA);

        fragmentA.dados_update("ON", "00:00:01", "00:00:02", "00:00:03");//Envia os dados para o OneFragment

        Toast.makeText(getActivity(),"Dados enviados!",Toast.LENGTH_LONG).show();
    }
};

}
    
asked by anonymous 30.06.2016 / 02:07

1 answer

4

Much like you get data via putExtra on Activity .

First of all, you need to refactor the setupViewPager method:

private OneFragment oneFragment;
private TwoFragment twoFragment;

private void setupViewPager(ViewPager viewPager) {
    oneFragment = new OneFragment();
    twoFragment = new TwoFragment();
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(oneFragment, "One");
    adapter.addFrag(twoFragment, "Two");
    viewPager.setAdapter(adapter);
}

And the timing method that sends the data too:

//Envia dados para o fragment OneFragment
public void enviaMensagemParaOFragment(String message, Fragment fragment){
    Bundle bundle = new Bundle();
    bundle.putString("CHAVE_DO_VALOR_PASSADO", message);
    fragment.setArguments(bundle);
}

And in your Activity you call the enviaMensagemParaOFragment method passing as a parameter string you want to send and Fragment to which it will be sent to string :

protected void onCreate(Bundle savedInstanceState) {

    ...

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    enviaMensagemParaOFragment("Essa é a mensagem que será enviada", oneFragment);

    ...
}

Now to recover the value, just change the method onCreateView of Fragment :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    String message = getArguments().getString("CHAVE_DO_VALOR_PASSADO");
    View myFragmentView = inflater.inflate(R.layout.fragment_two, container, false);

    ...
}

Even if you happen to want to call Fragment in the event of a click of a button for example, you can create a interface with a passarInformacao method, implement that interface from its Fragment and call this method directly from Activity .

InformationFile.java

public interface PassadorDeInformacao {
    public void passaInformacao(String informacao);
}

OneFragment.java and TwoFragment.java

public class OneFragment extends Fragment implements PassadorDeInformacao {

    @Override
    public void passaInformacao(String informacao) {
        // Faça o que quiser com a informação
        Log.d("OneFragment", "Recebi a informação: " + informacao);
    }

    ...
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    ...


    //Envia dados para o fragment OneFragment
    public void enviaMensagemParaOFragment(String message, PassadorDeInformacao fragment){
        fragment.passaInformacao(message);
    }

    private void onButtonClick() {
        enviaMensagemParaOFragment("minha mensagem", oneFragment);
    }

    ...
}

I hope I have helped \ o /

    
30.06.2016 / 02:39