从一个 Activity 将数据传递给另一个 Activity 中的 Fragment。

huangapple go评论73阅读模式
英文:

Pass data from Activity to Fragment in another Activity

问题

我需要从 Activity "MainCalendar" 传递数据到 Activity "Add" 中的 Fragment "AddTaskFragment"在一个 Fragment 中我有一个按钮点击该按钮会打开一个名为 "MainCalendar" 的 Activity在此 Activity 中我可以选择日历中的日期然后我需要将选定的日期传递到 Fragment 中

当我点击 "Choose" 按钮时会打开一个 "MainCalendar"用户需要选择日期之后 Activity 关闭然后我希望将 "MainCalendar" 中选择的日期放到 "Choose" 按钮的文本中

MainCalendar Activity:

MainCalendar Activity:

MainCalendar.class:

public class MainCalendar extends AppCompatActivity {
    // ... (略去未翻译部分)
}

Add.class:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);
    // ... (略去未翻译部分)
    String date = null;
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        // 此处的键值必须与其他 Activity 中使用的键值相匹配
        date = extras.getString("DATE_KEY");
    }
    // ... (略去未翻译部分)
}

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);
    // ... (略去未翻译部分)
    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");
    // ... (略去未翻译部分)
}

(代码已经被压缩,可能需要根据需要进行进一步的调整和格式化。)

英文:

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".

从一个 Activity 将数据传递给另一个 Activity 中的 Fragment。

MainCalendar Activity:

从一个 Activity 将数据传递给另一个 Activity 中的 Fragment。

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

答案1

得分: 0

有两种方法可以实现这个。第一种方法是使用回调(callback),第二种方法是使用 Bundle。
在第一种方法中,您可以创建一个接口并在片段中实现,然后将其传递给活动。当用户点击日期时,您通过此接口回调参数。
第二种方法是使用 Bundle,如下所示。
在您的片段中创建一个类似这样的构造函数,并在活动中调用它:

public static YourFragment getInstance(obj yourParameter){
    Bundle bundle = new Bundle();
    bundle.putString("edttext", "来自活动");
    // 设置片段类参数
    YourFragment fragobj = new YourFragment ();
    fragobj.setArguments(bundle);
    return fragobj;
}

在 onCreate 方法中以这种方式获取 obj:

String strtext = getArguments().getString("edttext");
英文:

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

huangapple
  • 本文由 发表于 2020年9月28日 23:06:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64104804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定