java - 使用 Bundle 将数据从 Activity 发送到 Fragment

标签 java android android-studio android-fragments dialog

我正在尝试使用 Bundle 将数据从 Activity 发送到 fragment 。当用户单击操作栏添加图标时,该 Activity 正在接收来自对话框的输入。该按钮还会打开对话框,但它将数据直接发送到 fragment (我试图了解 Activity 和 fragment 之间的区别并与对话框 fragment 进行交互)。互联网上的解决方案都不适合我,我希望有人能提供帮助

我提供了一个可视化来帮助我解释这个问题。因此,最初,我单击打开对话框的操作添加图标(第二张图),当我输入输入时,它不会更改 fragment 上的数据。仅当我第二次按下操作添加图标时,第一个输入才会更新(第3张图)。此外,您可能会注意到它显示“Bundle{[Dialog Input = First Input]}”,其中 First Input 是用户输入。我如何将其更改为“第一个输入”。我尝试在设置值之前清除 TextView ,但这不起作用。现在,最后当我按下按钮时,它会打开对话框,当我输入数据时,来自操作添加图标的数据(在 Activity 中处理,然后将数据发送到 fragment )与来自按钮的数据(直接发送到 fragment 的数据)重叠。任何帮助,将不胜感激。提前致谢。

enter image description here

主要 Activity :

public class MainActivity extends AppCompatActivity implements 
MyCustomDialog.OnInputSelected{

public String dialogInput;
FragmentManager fragmentManager;

@Override
public void sendInput(String input) {
    dialogInput = input;
}

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

    fragmentManager = getSupportFragmentManager();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //Inflate the menu, this adds items to the action bar if it is present
    getMenuInflater().inflate(R.menu.menu, menu);

    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    //Handle action bar clicks here. The action bar will automatically handle clicks on the home/up button
    //so long as you specify a parent activity in AndroidManifest.xml

    switch(item.getItemId()){

        case R.id.action_add:
            MyCustomDialog dialog = new MyCustomDialog();
            dialog.show(getSupportFragmentManager(), "MyCustomDialog");

            //Trying Bundle to pass data, dialog input between activity and fragment
            Bundle bundle = new Bundle();
            bundle.putString("Dialog Input", dialogInput);
            //Set Fragment class arguments
            MainFragment fragment = new MainFragment();
            fragment.setArguments(bundle); //set argument bundle to fragment

            fragmentManager.beginTransaction().replace(R.id.MainFragment,fragment).commit(); //now replace Mainfragment


            Toast.makeText(this, "Action_Add Clicked Successfully", Toast.LENGTH_SHORT).show();
    }

    return super.onOptionsItemSelected(item);
}
}

主要 fragment :

public class MainFragment extends Fragment implements MyCustomDialog.OnInputSelected{

TextView InputDisplay;
Button OpenDialog;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);

    InputDisplay = view.findViewById(R.id.InputDisplay);
    OpenDialog = view.findViewById(R.id.Open_Dialog);

    //Getting Main Activity dialog information with Bundle, that was received from toolbar add
    Bundle bundle = getArguments();
    if(bundle != null){
        String dialogInput = bundle.toString();
        //Clearing since Fragment call and activity call overlap each other.
        InputDisplay.setText("");
        InputDisplay.clearComposingText();
        InputDisplay.setText(dialogInput);
    }
    //String dialogInput = this.getArguments().getString("Dialog Input");

    OpenDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("MainFragment", "onClick: opening dialog");

            MyCustomDialog customDialog = new MyCustomDialog();
            customDialog.setTargetFragment(MainFragment.this, 1);
            customDialog.show(getFragmentManager(), "MyCustomDialog");
        }
    });

    return view;
}

@Override
public void sendInput(String input) {
    InputDisplay.setText("");
    InputDisplay.setText(input);
}
}

我的自定义对话框:

public class MyCustomDialog extends DialogFragment {

private EditText Input;
private TextView ActionOK, ActionCANCEL;

private OnInputSelected onInputSelected;

public interface OnInputSelected{
    void sendInput(String input);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        Fragment onInputSelected_fragment = getTargetFragment();
        Activity onInputSelected_activity = getActivity();
        if(onInputSelected_fragment != null){
            onInputSelected = (OnInputSelected) onInputSelected_fragment;
        }else{
            onInputSelected = (OnInputSelected) onInputSelected_activity;
        }
        //throw new RuntimeException("Custom Dialog onAttach Listener was NULL");
    }catch(ClassCastException e){
        Log.e("Custom Dialog", "onAttach: ClassCastException: " + e.getMessage());
    }
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialog_my_custom, container, false);

    Input = view.findViewById(R.id.Input);
    ActionOK = view.findViewById(R.id.Action_OK);
    ActionCANCEL = view.findViewById(R.id.Action_CANCEL);

    ActionCANCEL.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getDialog().dismiss();
        }
    });

    ActionOK.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onInputSelected.sendInput(Input.getText().toString());

            getDialog().dismiss();
        }
    });

    return view;
}
}

最佳答案

How do I change this to just, First Input.

您的输出打印如下“Bundle{[Dialog Input = First Input]}”,因为您直接执行bundle.toString();,而不是获取存储在bundle中的值。
将上面的内容改成这样

String dialogInput = bundle.getString("Dialog Input")
InputDisplay.setText(dialogInput);

the data from the action add icon overlaps with the data from the button

在像这样设置新值之前清除 TextView 中的现有文本

String dialogInput = bundle.getString("Dialog Input")
InputDisplay.setText(");
InputDisplay.setText(dialogInput);

此外,我注意到您使用的所有变量名称都不遵循驼峰式大小写,我建议您也更正这一点。

关于java - 使用 Bundle 将数据从 Activity 发送到 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957005/

相关文章:

java - 为什么我的 move() 方法不能将球保持在界内?

java - 从 pstree 获取所有 pid

android - ActionBar 自定义标题颜色

java - 在java命令行中获取多行输入

Java:组合数组中的计数以获得百分比

java - 当用户想要应用程序中的另一种颜色时如何更改颜色?

java - 安卓/MongoDB : "NoClassDefFoundError: com.mongodb.DBPortPool"

android - 谷歌地图关闭后开始 Activity

java - 如何在另一个线程上运行 RxJava 观察者

android-studio - 创建新项目时更改默认的 gitignore 文件