从另一个片段调用方法

时间:2019-02-17 08:02:16

标签: java android android-fragments methods

当我单击fragment2中的fab时,如何在fragment1中调用方法insertItem()?因此我可以在片段1的recyclerview中添加项目。顺便说一句,我正在使用BottomNavigationView,所以findFragmentById对我不起作用。搜索时看到的全部是findFragmentById,但是如果我没有实现XML fragment,该怎么办,我将其添加到了布局资源中。.

主要活动/按键的代码

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));
        }
    }


}

片段代码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();


    }

}

片段代码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;
    }

}

1 个答案:

答案 0 :(得分:0)

基本上,您希望片段彼此通信。我将对此进行简要说明,但有关更多详细信息,请参阅此android文档https://developer.android.com/training/basics/fragments/communicating

您需要在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");
        }
    }

在FAB Click侦听器中调用onExpenseUpdate()方法,并让您的活动实现ExpenseListener接口。

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

然后在覆盖的onExpenseUpdate()方法中,您可以调用第二个片段的方法。希望它能回答您的问题。