如何从一个片段通过另一个片段获取数据?

时间:2019-04-13 01:32:00

标签: android android-fragments

我正在处理两个片段,一个称为图,另一个称为函数。 在图形中,用户可以使用节点和边来绘制图形。 在“功能”中,用户可以选择算法或图论功能。

当我在Fragment函数中时,我试图从Fragment Graph中获取数据,但这返回了null错误,并且“ Fragment未连接到上下文” 已经尝试使用bundle和interface。

创建边缘,我能够在界面中使用捆绑包,并将数据传递给对话框,用户可以在其中选择节点并创建边缘。

这是我的标签页:

public class Tab extends AppCompatActivity implements FragmentGrafo.TexteData {
    private Toolbar toolbar;
    private boolean orientado;
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null){
            orientado = Objects.requireNonNull(getIntent().getExtras()).getBoolean("orientado");
        }
        toolbar = findViewById(R.id.toolbar_tab);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        if (orientado){
           this.toolbar.setTitle(getString(R.string.txt_toolbar_tab_orientado));
        } else {
            toolbar.setTitle(R.string.txt_toolbar_tab_nao_orientado);
        }
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        if (orientado) {
            adapter.AddFragment(new FragmentGrafoOrientado(), getString(R.string.txt_tab_grafo));
            adapter.AddFragment(new FragmentFuncoes(), getString(R.string.txt_tab_funcoes));
        } else {
            adapter.AddFragment(new FragmentGrafo(), getString(R.string.txt_tab_grafo));
            adapter.AddFragment(new FragmentFuncoes(), getString(R.string.txt_tab_funcoes));
        }

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void Data(String s) {
        FragmentFuncoes f = new FragmentFuncoes();
        Bundle b = new Bundle();
        b.putString("key", s);
        f.setArguments(b);
    }
}

这是我的FragmentGrafo:

public class FragmentGrafo extends Fragment implements DialogAddAresta.HelperAddAresta, DialogDeletar.HelperDeletar {

    private TexteData mListener;
    private BottomNavigationView bottomNavigationView;
    private Graph graph;
    private DefaultFragment fragment;
    private String[] alfabeto = new String[]{"A","B","C","D","E","F","G","H","I","J","K",
            "L","M","N","O","P","Q","R","S","T","U","V","X","W","Y","Z"};
    private int alfaPos = 0;
    private float x = 0.0f, y = 0.0f;
    private List<String> listNos = new ArrayList<>();
    private List<String> listArestas = new ArrayList<>();

    private String styleSheet = "graph { fill-color: #CDCDCD; }" +
            "node { size: 100px; text-size: 30px; fill-color: white; stroke-mode: plain; }" +
            "node:clicked { fill-color: #007FFF; }" ;

    public FragmentGrafo() {}

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.activity_fragment_grafo, container, false);

        bottomNavigationView = view.findViewById(R.id.bottomNavView);
        bottomNavigationView.setOnNavigationItemSelectedListener(selectedListener);

        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        graph = new SingleGraph("AthenaGraph");
        graph.setAttribute("ui.stylesheet", styleSheet);
        graph.setAttribute("ui.antialias");
        display(savedInstanceState, graph, false);
    }

    private BottomNavigationView.OnNavigationItemSelectedListener selectedListener
            = menuItem -> {
                switch (menuItem.getItemId()){
                    case R.id.add_no:
                        addNo();
                        return true;

                    case R.id.add_aresta:
                        openDialogAddAresta();
                        return true;

                    case R.id.deletar:
                        openDialogDeletar();
                        return true;
                }
                return false;
            };

    public void display(Bundle savedInstanceState, Graph graph, boolean autoLayout) {
        if (savedInstanceState == null) {
            FragmentManager fm = Objects.requireNonNull(getActivity()).getFragmentManager();
            fragment = (DefaultFragment) fm.findFragmentByTag("fragment_tag");

            if (null == fragment) {
                fragment = new DefaultFragment();
                fragment.init(graph, autoLayout);
            }

            FragmentTransaction ft = fm.beginTransaction() ;
            ft.add(R.id.frameLayout, fragment).commit();
        }
    }

    public void addNo(){
        if (alfaPos < alfabeto.length){
            String aux = alfabeto[alfaPos];
            graph.addNode(aux);
            graph.getNode(aux).setAttribute("ui.label", aux);
            graph.getNode(aux).setAttribute("xyz", x, y, 0);
            listNos.add(aux);
            alfaPos++;
            x += 0.5f;
            y += 0.5f;
        } else {
            Toast.makeText(getActivity(), getResources().getString(R.string.txt_no_maximo), Toast.LENGTH_SHORT).show();
        }
    }

    private void openDialogAddAresta() {
        DialogAddAresta dialogAddAresta = new DialogAddAresta();

        Bundle bundle = new Bundle();
        bundle.putStringArrayList("listNos", (ArrayList<String>) listNos);
        dialogAddAresta.setTargetFragment(FragmentGrafo.this, 1);
        dialogAddAresta.setArguments(bundle);
        dialogAddAresta.show(Objects.requireNonNull(getActivity()).getSupportFragmentManager(), getString(R.string.txt_add_aresta));
    }

    @Override
    public void applyAddAresta(String noFrom, String noTo, String peso) {
        String nomeAresta = noFrom + noTo;
        String nomeArestaInvertido = noTo + noFrom;
        int tam = graph.getEdgeCount(), count = 0;
        // Se tam for == 0 nao tem aresta entao cria uma direto.
        if (tam == 0){
            if (peso.equals("")) {
                peso = "1";
                graph.addEdge(nomeAresta, noFrom, noTo, false)
                        .setAttribute("length", peso);
                listArestas.add(nomeAresta);
            } else {
                graph.addEdge(nomeAresta, noFrom, noTo, false)
                        .setAttribute("length", peso);
                graph.getEdge(nomeAresta).setAttribute("ui.label", peso);
                listArestas.add(nomeAresta);
            }
        }
        if (tam != 0){
            for (int i = 0; i < tam; i++){
                String compara = graph.getEdge(i).getId();
                if (compara.equals(nomeAresta) || compara.equals(nomeArestaInvertido)){
                    count = 1;
                }
            }
        }
        if (count == 1){
            Toast.makeText(getActivity(), R.string.txt_aresta_existente, Toast.LENGTH_SHORT).show();
        } else if (tam >= 1){
            if (peso.equals("")) {
                peso = "1";
                graph.addEdge(nomeAresta, noFrom, noTo, false)
                        .setAttribute("length", peso);
                listArestas.add(nomeAresta);
            } else {
                graph.addEdge(nomeAresta, noFrom, noTo, false)
                        .setAttribute("length", peso);
                graph.getEdge(nomeAresta).setAttribute("ui.label", peso);
                listArestas.add(nomeAresta);
            }
        }
    }
    private void openDialogDeletar(){
        DialogDeletar dialogDeletar = new DialogDeletar();

        Bundle bundle = new Bundle();
        bundle.putStringArrayList("listNos", (ArrayList<String>) listNos);
        bundle.putStringArrayList("listArestas", (ArrayList<String>) listArestas);

        dialogDeletar.setTargetFragment(FragmentGrafo.this, 1);
        dialogDeletar.setArguments(bundle);
        dialogDeletar.show(Objects.requireNonNull(getActivity()).getSupportFragmentManager(), getString(R.string.txt_deletar));
    }

    @Override
    public void applyDeletar(String deletaNo, String deletaAresta, boolean controle) {
        if (controle){
            graph.removeNode(deletaNo);
            listNos.remove(deletaNo);
            atualizaListas(deletaNo);
        } else {
            graph.removeNode(deletaAresta);
            listArestas.remove(deletaAresta);
        }

    }

    private void atualizaListas(String item){
        int tam = graph.getEdgeCount();
        listArestas.clear();
        for (int i = 0; i < tam; i++){
            listArestas.add(graph.getEdge(i).getId());
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof TexteData) {
            mListener = (TexteData) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

//this was just a test to see if the Toast works
    public void vamos(){
        Toast.makeText(getActivity(), getResources().getString(R.string.txt_no_maximo), Toast.LENGTH_SHORT).show();
    }

    public interface TexteData{
        void Data(String s);
    }
}

这是我的FragmentFuncoes:

public class FragmentFuncoes extends Fragment {

    private Spinner spinner;
    private ImageButton btnRun, btnExecurar;
    private TextView tvResp;
    private String item;
    private boolean run = true;

    public FragmentFuncoes() {}

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.activity_fragment_funcoes, container, false);

        spinner = view.findViewById(R.id.spFuncoes);
        btnRun = view.findViewById(R.id.btnRun);
        btnExecurar = view.findViewById(R.id.btnExecutar);
        tvResp = view.findViewById(R.id.tvLinha2);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(Objects.requireNonNull(getContext()),
                android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.funcoes));
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(arrayAdapter);

        spinner.setOnItemSelectedListener(spinnerSelected);
        btnRun.setOnClickListener(btnRunClicked);
        btnExecurar.setOnClickListener(btnExecutarClicked);

        return view;
    }

    private Spinner.OnItemSelectedListener spinnerSelected =
            new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    item = spinner.getSelectedItem().toString();
                    switch (item){
                        case "***":
                            tvResp.setText("Escolha um funcionalidade");
                            break;

                        case "Informações Gerais":
                            tvResp.setText("Execute para ver as informacoes do grafo.");
                            break;

                        case "Dijkstra":
                            Toast.makeText(getContext(),"teste selecionou Dijkstra",Toast.LENGTH_SHORT).show();
                            break;

                        case "Coloração":
                            Toast.makeText(getContext(),"teste selecionou Coloração",Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            };

    private ImageButton.OnClickListener btnExecutarClicked =
            v -> {
                switch (item){
                    case "***":
                        Toast.makeText(getContext(),"teste selecionou *** - executar",Toast.LENGTH_SHORT).show();
                        break;

                    case "Informações Gerais":
                        getInformacoesGerais();
                        break;

                    case "Dijkstra":
                        Toast.makeText(getContext(),"teste selecionou Dijkstra - executar",Toast.LENGTH_SHORT).show();
                        break;

                    case "Coloração":
                        Toast.makeText(getContext(),"teste selecionou Coloração - executar",Toast.LENGTH_SHORT).show();
                        break;
                }
            };

    private ImageButton.OnClickListener btnRunClicked =
            v -> {
                if (run){
                    btnRun.setImageResource(R.drawable.ic_slow_run);
                    Toast.makeText(getContext(), getResources().getString(R.string.btn_run_slow), Toast.LENGTH_SHORT).show();
                    run = false;
                } else {
                    btnRun.setImageResource(R.drawable.ic_fast_run);
                    Toast.makeText(getContext(), getResources().getString(R.string.btn_run_fast), Toast.LENGTH_SHORT).show();
                    run = true;
                }
            };

    private void getInformacoesGerais(){
        FragmentGrafo fragmentGrafo = new FragmentGrafo();
        fragmentGrafo.vamos();
    }
}

我该在哪里弄错数据?

1 个答案:

答案 0 :(得分:0)

我这样做是这样的:-

YourSecondFragment fragment = new YourSecondFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
fragment .setArguments(args);
getFragmentManager().beginTransaction().add(R.id.container, fragment ).commit();

在YourSecondFragment的onCreateView中:

String value = getArguments().getString("YourKey");