programing

일부 데이터를 다른 조각으로 전송하는 방법은 무엇입니까?

itmemos 2023. 9. 4. 19:35
반응형

일부 데이터를 다른 조각으로 전송하는 방법은 무엇입니까?

일부 데이터를 다른 데이터로 전송하는 방법Fragment마찬가지로 그것은 끝이 났습니다.extras위해서intents?

사용Bundle다음은 예입니다.

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

번들은 많은 데이터 유형에 대한 메서드를 제공합니다. 항목 보기

그럼 당신의Fragment다음을 사용하여 데이터 검색(예: 방법):

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}

Ankit가 말했듯이 이전 답변을 더욱 확장하려면 복잡한 개체에 대해 Serializable을 구현해야 합니다.예를 들어, 단순 개체의 경우:

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}

FromFragment에서:

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();

ToFragment에서:

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

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

getArguments()가 null을 반환하는 이유는 "It's got 아무 것도 얻지 못했기 때문입니다."

이 상황을 처리하려면 이 코드를 사용하십시오.

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}

fragment to fragment를 사용하여 데이터를 전달하는 전체 코드

Fragment fragment = new Fragment(); // replace your custom fragment class 
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                bundle.putString("key","value"); // use as per your need
                fragment.setArguments(bundle);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(viewID,fragment);
                fragmentTransaction.commit();

사용자 정의 조각 클래스

Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key);  // key must be same which was given in first fragment

이전 답변을 확장하기 위해 - 누군가에게 도움이 될 수 있습니다.만약 당신이getArguments()돌아온다null에 힘쓰다onCreate()메소드 및 fragment 생성자가 아님:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int index = getArguments().getInt("index");
}

코틀린을 사용하고 있다면 통과할 수 있습니다.bundle~하듯이

val fragment = YourFragment()
val bundle = Bundle().apply {
    putInt("someInt", 5)
    putString("someString", "Hello")
}
fragment.arguments = bundle

그리고 이 값들을 가져옵니다.YourFragmentonCreate~하듯이

this.arguments?.let {
    val someInt    = it.getInt("someInt", someDefaultInt)
    val someString = it.getString("someString", someDefaultString)
}

번들 사용 방법은 다음과 같습니다.

Bundle b = new Bundle();
b.putInt("id", id);
Fragment frag= new Fragment();
frag.setArguments(b);

번들에서 값 검색:

 bundle = getArguments();
 if (bundle != null) {
    id = bundle.getInt("id");
 }

그래프를 사용하여 조각 간을 탐색하는 경우 다음 작업을 수행할 수 있습니다.조각 A에서:

    Bundle bundle = new Bundle();
    bundle.putSerializable(KEY, yourObject);
    Navigation.findNavController(view).navigate(R.id.fragment, bundle);

조각 B:

    Bundle bundle = getArguments();
    object = (Object) bundle.getSerializable(KEY);

물론 개체는 직렬화 가능한 기능을 구현해야 합니다.

            First Fragment Sending String To Next Fragment
            public class MainActivity extends AppCompatActivity {
                    private Button Add;
                    private EditText edt;
                    FragmentManager fragmentManager;
                    FragClass1 fragClass1;


                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        Add= (Button) findViewById(R.id.BtnNext);
                        edt= (EditText) findViewById(R.id.editText);

                        Add.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                fragClass1=new FragClass1();
                                Bundle bundle=new Bundle();

                                fragmentManager=getSupportFragmentManager();
                                fragClass1.setArguments(bundle);
                                bundle.putString("hello",edt.getText().toString());
                                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                                fragmentTransaction.add(R.id.activity_main,fragClass1,"");
                                fragmentTransaction.addToBackStack(null);
                                fragmentTransaction.commit();

                            }
                        });
                    }
                }
         Next Fragment to fetch the string.
            public class FragClass1 extends Fragment {
                  EditText showFrag1;


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

                        View view=inflater.inflate(R.layout.lay_frag1,null);
                        showFrag1= (EditText) view.findViewById(R.id.edtText);
                        Bundle bundle=getArguments();
                        String a=getArguments().getString("hello");//Use This or The Below Commented Code
                        showFrag1.setText(a);
                        //showFrag1.setText(String.valueOf(bundle.getString("hello")));
                        return view;
                    }
                }
    I used Frame Layout easy to use.
    Don't Forget to Add Background color or else fragment will overlap.
This is for First Fragment.
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@color/colorPrimary"
        tools:context="com.example.sumedh.fragmentpractice1.MainActivity">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/BtnNext"/>
    </FrameLayout>


Xml for Next Fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
   android:background="@color/colorAccent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtText"/>

</LinearLayout>

활동 클래스에서:

번들 인수를 사용하여 fragment로 데이터 전송 및 fragment 로드

   Fragment fragment = new myFragment();
   Bundle bundle = new Bundle();
   bundle.putString("pName", personName);
   bundle.putString("pEmail", personEmail);
   bundle.putString("pId", personId);
   fragment.setArguments(bundle);

   getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    fragment).commit();

내 단편 수업에서:

번들에서 인수를 가져와 xml로 설정합니다.

    Bundle arguments = getArguments();
    String personName = arguments.getString("pName");
    String personEmail = arguments.getString("pEmail");
    String personId = arguments.getString("pId");

    nameTV = v.findViewById(R.id.name);
    emailTV = v.findViewById(R.id.email);
    idTV = v.findViewById(R.id.id);

    nameTV.setText("Name: "+ personName);
    emailTV.setText("Email: "+ personEmail);
    idTV.setText("ID: "+ personId);

입력 조각

public class SecondFragment extends Fragment  {


    EditText etext;
    Button btn;
    String etex;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.secondfragment, container, false);
        etext = (EditText) v.findViewById(R.id.editText4);
        btn = (Button) v.findViewById(R.id.button);
        btn.setOnClickListener(mClickListener);
        return v;
    }

    View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            etex = etext.getText().toString();
            FragmentTransaction transection = getFragmentManager().beginTransaction();
            Viewfragment mfragment = new Viewfragment();
            //using Bundle to send data
            Bundle bundle = new Bundle();
            bundle.putString("textbox", etex);
            mfragment.setArguments(bundle); //data being send to SecondFragment
            transection.replace(R.id.frame, mfragment);
            transection.isAddToBackStackAllowed();
            transection.addToBackStack(null);
            transection.commit();

        }
    };



}

당신의 견해 단편

public class Viewfragment extends Fragment {

    TextView txtv;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.viewfrag,container,false);
        txtv = (TextView)  v.findViewById(R.id.textView4);
        Bundle bundle=getArguments();
        txtv.setText(String.valueOf(bundle.getString("textbox")));
        return v;
    }


}

언급URL : https://stackoverflow.com/questions/7149802/how-to-transfer-some-data-to-another-fragment

반응형