簡體   English   中英

如何將數據從活動 A 傳遞到活動 B 中的片段?

[英]How to pass data from Activity A to fragment in Activity B?

我需要將數據從活動“MainCalendar”傳遞到活動“Add”中的片段“AddTaskFragment”。 我在一個片段中有一個按鈕,它打開一個活動“MainCalendar”,我在日歷中選擇一個日期,然后我需要將此日期發送到一個片段中。

當我單擊“選擇按鈕”時,會打開一個 MainCalendar,用戶需要在其中選擇日期,然后活動關閉,然后我想將 MainCalendar 中的日期添加到“選擇按鈕”的文本中。

添加帶有片段的活動,MainCalendar 活動: MainCalendar

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

    });
}

添加.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,它在 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);
}

據我了解,您必須進行活動( Activity AActivity B )並且您在活動 B 中有一個片段。您想要做的是出於任何原因將一些數據從活動 A 發送到該片段。

讓我們先說明一下,您不能在不啟動活動的情況下直接將數據發送到活動的任何片段。 因此,為了將此數據發送到片段,您必須首先將其從Activity A傳遞到Activity B ,然后作為第二步將其從Activity B發送到Fragment

數據類型非常重要。 如果您要發送自定義類型(模型 java 類),則必須將其定義為Parcelable或者如果它是原始類型(例如intfloat ,則您可以直接發送它

這是如何在Java中做到這一點

活動A.java

class ActivityA extends Activity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activityA);

        // define your data here
        int data = 5;

        // define an intent to send the data to the second activity
        Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
        intent.putExtra("DATA_KEY", data);
        startActivity(intent);

    }
}

那么我們需要做的是

  • 接收Activity B的數據
  • 膨脹片段
  • 將數據傳遞給片段
class ActivityB extends Activity{


    Int data;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activityB);

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

        // Fragment instance
        FragmentClass frag = new FragmentClass();

        Bundle bundle = new Bundle();
        bundle.putInt("DATA_KEY", data );
        frag.setArguments(bundle);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, mFeedFragment);
        fragmentTransaction.commit();
        

    }
}

然后按照我們在Activity B接收它的方式接收它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM