简体   繁体   中英

Pass data from Activity to Fragment in another Activity

I need to pass data from Activity "MainCalendar" to fragment "AddTaskFragment" in Activity "Add". I have a button in a fragment which opens an Activity "MainCalendar", where I select a date in the calendar, and then I need to send this date into a fragment.

When I click on Choose Button, there is opens a MainCalendar, where user need to choose date, after that, the activity closed, and than I want to put a date from MainCalendar to the text of "Choose Button".

使用片段添加活动

MainCalendar Activity:

主日历

MainCalendar.class:

public class MainCalendar extends AppCompatActivity {
private CalendarView Calendar;
private String date;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_calendar);
    Calendar = (CalendarView) findViewById(R.id.calendarView);



    Calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
            date = (dayOfMonth+"/"+month+"/"+year);
            System.out.println(date);
            Intent intent = new Intent(MainCalendar.this, Add.class);
            intent.putExtra("DATE_KEY", date);
            finish();
        }

    });
}

Add.class:

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

    BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
    bottomNav.setSelectedItemId(R.id.add);
    Button notes_button = findViewById(R.id.notes_btn);
    Button tasks_button = findViewById(R.id.tasks_btn);
    Button goals_button = findViewById(R.id.goals_btn);
    RadioButton rb = findViewById(R.id.choose_day_btn);


    String date = null;
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        //The key argument here must match that used in the other activity
        date = extras.getString("DATE_KEY");
    }

    AddTasksFragment frag = new AddTasksFragment();

    Bundle bundle = new Bundle();
    bundle.putString("DATE_KEY", date);
    frag.setArguments(bundle);

    Fragment fragment1 = new AddTasksFragment();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment1).commit();


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

            switch (item.getItemId()){
                case R.id.notes:
                    startActivity(new Intent(getApplicationContext(), Notes.class));
                    overridePendingTransition(0,0);
                    return true;
                case R.id.add:
                    return true;
                case R.id.tasks:
                    startActivity(new Intent(getApplicationContext(), Tasks.class));
                    overridePendingTransition(0,0);
                    return true;
                case R.id.goals:
                    startActivity(new Intent(getApplicationContext(), Goals.class));
                    overridePendingTransition(0,0);
                    return true;
                case R.id.statistics:
                    startActivity(new Intent(getApplicationContext(), Statistics.class));
                    overridePendingTransition(0,0);
                    return true;

            }
            return false;
        }
    });

    Fragment fragment = new AddTasksFragment();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();

    tasks_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Fragment fragment = new AddTasksFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
        }
    });

    notes_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Fragment fragment = new AddNotesFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
        }
    });

    goals_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Fragment fragment = new AddGoalsFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
        }
    });

//

AddTaskFragment.class, which is in Add.class:

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

    return inflater.inflate(R.layout.add_tasks_fragment, container, false);

    }

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    subtask_btn = (Button) view.findViewById(R.id.add_subtask_btn);
    subtask_name = (EditText) view.findViewById(R.id.subtask_name);
    task_name = (EditText) view.findViewById(R.id.task_name);
    lin_lay = (LinearLayout) view.findViewById(R.id.linear_layout);
    sb_lay = (LinearLayout) view.findViewById(R.id.subtask_lay);
    apply_btn = (Button) view.findViewById(R.id.apply_btn);

    rgDay = (RadioGroup) view.findViewById(R.id.date_group);
    rgPriority = (RadioGroup) view.findViewById(R.id.priority_group);
    todayBtn = (RadioButton) view.findViewById(R.id.today_btn);
    tomorrowBtn = (RadioButton) view.findViewById(R.id.tomorrow_btn);
    chooseDayBtn = (RadioButton) view.findViewById(R.id.choose_day_btn);
    lowPrBtn = (RadioButton) view.findViewById(R.id.low_btn);
    mediumPrBtn = (RadioButton) view.findViewById(R.id.medium_btn);
    highPrBtn = (RadioButton) view.findViewById(R.id.high_btn);


    firebaseAuth = FirebaseAuth.getInstance();
    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    dataBase = FirebaseDatabase.getInstance().getReference(TASKS_KEY);
    this.getResources().getDisplayMetrics();


    subtask_btn.setOnClickListener(this);
    apply_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            writeTask();
        }
    });
    chooseDayBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), MainCalendar.class);
            startActivity(intent);
        }
    });
    String data;
    data = getActivity().getIntent().getStringExtra(DATE_KEY);
    }

@Override
public void onClick(View v) {
    addView();
}



private void writeTask() {
    String Task;
    Task = task_name.getText().toString();
    dataBase.push().setValue(Task);

    String[] subTasks = new String[sb_lay.getChildCount()];
    for (int i = 0; i < sb_lay.getChildCount(); i++) {

        View subtaskView = sb_lay.getChildAt(i);

        EditText editTextName = (EditText) subtaskView.findViewById(R.id.subtask_name);
        subTasks[i] = editTextName.getText().toString();

        dataBase.child(Task).child("Subtasks").push().setValue(subTasks[i]);
        }
        dataBase.child(Task).push().setValue(getDay());
}

private String getDay(){
    String day=null;

    if(todayBtn.isChecked()){
        Date currentTime = Calendar.getInstance().getTime();
        day = currentTime.toString();
    }
    else if(tomorrowBtn.isChecked()){
        Date dt = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(dt);
        c.add(Calendar.DATE, 1);
        dt = c.getTime();
        day = dt.toString();
    }else if(chooseDayBtn.isChecked()) {
        day =  getArguments().getString("DATE_KEY");
        System.out.println(" Date is choosed ----------------------------------------------------------------------------" + day);
        chooseDayBtn.setText(day);
    }
    return day;
}

private void addView(){
    final View subtaskView = getLayoutInflater().inflate(R.layout.subtask_raw, null, false);

    EditText editText = (EditText)subtaskView.findViewById(R.id.subtask_name);
    ImageView imageClose = (ImageView)subtaskView.findViewById(R.id.remove_subtask);

    imageClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            removeView(subtaskView);
        }
    });

    sb_lay.addView(subtaskView);
    String day;
    day =  getArguments().getString("DATE_KEY");
    System.out.println(" Date is choosed " + day);

}

private void removeView(View view){
    sb_lay.removeView(view);
}

There are two ways to do that. The first one is using callback and the second one is using a bundle. In the first-way, you can create an interface and implement in your fragment and pass it to your activity. when users click the date you callback the parameter using this interface. The second-way using bundles like this. in your fragment create a constructor like this and call it in your activity :

public static YourFragment getInstance(obj yourParameter){
    Bundle bundle = new Bundle();
    bundle.putString("edttext", "From Activity");
    // set Fragmentclass Arguments
    YourFragment fragobj = new YourFragment ();
    fragobj.setArguments(bundle);
return fragobj;
}

in the onCreate method get obj in this way :

String strtext = getArguments().getString("edttext"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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