简体   繁体   English

从另一个片段调用方法

[英]Calling method from another fragment

how can I call the method insertItem() in the fragment1 when I click the fab in the fragment2? 单击fragment2中的fab时,如何在fragment1中调用方法insertItem() so I can add items in the recyclerview in my fragment 1.. BTW I am using BottomNavigationView so findFragmentById won't work for me.. All I see when I search is findFragmentById , but what if in my case I don't have XML implemented fragment , I have it added in the layout resources.. 所以我可以在片段1的recyclerview中添加项目。顺便说一句,我正在使用BottomNavigationView所以findFragmentById对我不起作用。.搜索时看到的全部是findFragmentById ,但是如果我没有XML怎么办实现的fragment ,我在布局资源中添加了它。

CODE FOR MAIN ACTIVITY/SCREENONE 主要活动/并列代码

package com.example.admin.test2;

import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;


public class ScreenOne extends AppCompatActivity{


    BottomNavigationView bottomNavigationView;

    Income incomeFragment = new Income ();
    Expense expenseFragment = new Expense ();
    Savings savingsFragment = new Savings ();
    MainScreen mainFragment = new MainScreen ();
    Charts chartsFragment = new Charts ();

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

        bottomNavigationView = findViewById (R.id.Navbot);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId ()){
                    case R.id.home:
                        getSupportFragmentManager ().beginTransaction ().setCustomAnimations (R.anim.fade_in, R.anim.fade_out).replace (R.id.replaceLayout, mainFragment).commit ();
                        updateStatusBarColor("#77dd77");
                        return true;

                    case R.id.income:
                        getSupportFragmentManager ().beginTransaction ().setCustomAnimations (R.anim.fade_in, R.anim.fade_out).replace (R.id.replaceLayout, incomeFragment).commit ();
                        updateStatusBarColor("#779ecb");
                        return true;

                    case R.id.expense:
                        getSupportFragmentManager ().beginTransaction ().setCustomAnimations (R.anim.fade_in, R.anim.fade_out).replace (R.id.replaceLayout, expenseFragment).commit ();
                        updateStatusBarColor("#ff6961");
                        return true;

                    case R.id.savings:
                        getSupportFragmentManager ().beginTransaction ().setCustomAnimations (R.anim.fade_in, R.anim.fade_out).replace (R.id.replaceLayout, savingsFragment).commit ();
                        updateStatusBarColor("#77dd77");
                        return true;

                    case R.id.chart:
                        getSupportFragmentManager ().beginTransaction ().setCustomAnimations (R.anim.fade_in, R.anim.fade_out).replace (R.id.replaceLayout, chartsFragment).commit ();
                        updateStatusBarColor("#77dd77");
                        return true;

                }
                return false;
            }
        });
        bottomNavigationView.setSelectedItemId (R.id.home);


    }

    public void updateStatusBarColor(String color){// Color must be in hexadecimal fromat
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.parseColor(color));
        }
    }


}

CODE FOR FRAGMENT1 片段代码1

package com.example.admin.test2;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 */
public class MainScreen extends Fragment {

    private ArrayList <ExampleItem> mExampleList;

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_main_screen, container, false);

        DataHandlers dataHandlers = new DataHandlers();

        try {
            String deTails = dataHandlers.getDetails();
            int aMount = dataHandlers.getAmount();
            Toast.makeText(getActivity().getApplicationContext(), deTails + "" + aMount, Toast.LENGTH_LONG).show();
            //TAS DITO KA NA MAG SET TEXT SA MGA TEXTVIEW NG AMOUNT AT DETAILS

        } catch (Exception ex) {
            Toast.makeText(getActivity().getApplicationContext(), ex.getMessage().toString(), Toast.LENGTH_LONG).show();
        }

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        mExampleList = new ArrayList <>();
        mExampleList.add(new ExampleItem(R.drawable.food, "", "", "ADD EXPENSES"));


        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getContext());
        mAdapter = new ExampleAdapter(mExampleList);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        return view;
    }

    public void insertItem() {
        DataHandlers dataHandlers = new DataHandlers();

        String deTails = dataHandlers.getDetails();
        int aMount = dataHandlers.getAmount();

        mExampleList.add(0, new ExampleItem(R.drawable.food, "Food & Drink", "" + deTails, "₱ " + aMount));
        mAdapter.notifyDataSetChanged();


    }

}

CODE FOR FRAGMENT2 片段代码2

package com.example.admin.test2;


import android.app.DatePickerDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class Expense extends Fragment {



    public Expense() {
        // Required empty public constructor
    }
    //SPINNER
    Spinner sp1;
    CustomAdapter adapter;
    String[] names = {"Food & Drink", "Shopping", "Transportation", "Home", "Bills & Fees", "Entertainment", "Healthcare", "Education", "Beauty", "Others"};
    int[] images = {R.drawable.food, R.drawable.shopping, R.drawable.transportation, R.drawable.home, R.drawable.bills, R.drawable.entertainment, R.drawable.medical, R.drawable.education, R.drawable.beauty, R.drawable.others};

    //DATE PICKER
    private EditText mDisplayDate;
    private DatePickerDialog.OnDateSetListener mDateSetListener;

    //FOR THE ADD ITEM
    FloatingActionButton fab;

    EditText amount;
    EditText detail;

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate (R.layout.fragment_expense, container, false);


        //spinner
        sp1 = (Spinner)view.findViewById(R.id.customSpinner);

        adapter = new CustomAdapter(getActivity(), names, images);
        sp1.setAdapter(adapter);

        //fab onClick - sending values to the recycler view
        fab = (FloatingActionButton) view.findViewById(R.id.fabs);
        amount = (EditText) view.findViewById(R.id.textAmountt);
        detail = (EditText) view.findViewById(R.id.textDetailss);

        final DataHandlers dataHandlers = new DataHandlers();

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pos = sp1.getSelectedItemPosition();

                //DINAGDAG KO
                dataHandlers.setAmount(Integer.parseInt(amount.getText().toString()));
                dataHandlers.setDetails(detail.getText().toString());

            }
        });

        //int pos = sp1.getSelectedItemPosition();

        //date picker
        mDisplayDate = (EditText) view.findViewById(R.id.datePick);

        mDisplayDate.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog = new DatePickerDialog(getActivity(),
                        android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                        mDateSetListener,
                        year, month, day);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();

            }
        });

        mDateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int day) {
                //Calendar calendar = Calendar.getInstance();
                //String currentDate = DateFormat.getDateInstance().format(calendar.getTime());

                month = month + 1;
                String date = month + "-" + day + "-" + year;
                mDisplayDate.setText(date);


            }
        };

        return view;
    }

}

Basically you want fragments to communicate with each other. 基本上,您希望片段相互通信。 I will explain it briefly, but for more details you can refer this android doc https://developer.android.com/training/basics/fragments/communicating 我将对此进行简要说明,但有关更多详细信息,请参阅此android文档https://developer.android.com/training/basics/fragments/communicating

You need to define an interface in your Expense fragment, I am calling it ExpenseListener , you can change the method name and parameter according to your need. 您需要在Expense片段中定义一个接口,我称其为ExpenseListener ,您可以根据需要更改方法名称和参数。

public class Expense extends Fragment{
    ExpenseListener mCallback;

    public interface ExpenseListener{
        public void onExpenseUpdate(String amount);
    }
    ...

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // activity must implement
        // the callback interface. it throws an exception otherwise
        try {
            mCallback = (ExpenseListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement ExpenseListener");
        }
    }

Call onExpenseUpdate() method in your FAB click listener and have your activity implement the ExpenseListener interface. 在您的FAB Click侦听器中调用onExpenseUpdate()方法,并让您的活动实现ExpenseListener接口。

public class ScreenOne extends AppCompatActivity implements Expense.ExpenseListener{
    @Override
    public void onExpenseUpdate(String text){
        // call method of MainScreen
        mainFragment.insertItem();
    }
}

then in the overridden onExpenseUpdate() method, you can invoke the method of your 2nd fragment. 然后在覆盖的onExpenseUpdate()方法中,您可以调用第二个片段的方法。 Hope it answers your question. 希望它能回答您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM