簡體   English   中英

使用 EditText 將數據從片段傳遞到片段

[英]Using EditText to pass data from fragment to fragment

我使用 EditText 輸入一個整數值並在第一個片段中使用 Integer.parse 並使用接口將值發送到第二個片段。 我也應用了 ViewPager2。 我不太擅長使用 View Pager,因為這是我第一次使用它。 如果可能,請發布代碼。

所以我的問題是

  1. 我運行它的代碼哪里出錯了? (錯誤在於

    SM.sendData(Integer.parseInt(text1.getText().toString()));

    我不明白這是什么錯誤)

  2. 是否有另一種方法可以使用其他方法(例如 Bundle)來轉移價值?

第一個片段:

public class FirstFragment extends Fragment {

    private FragmentFirstBinding binding;
    SendMessage SM;

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

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        final EditText text1 = view.findViewById(R.id.text1);

        binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SM.sendData(Integer.parseInt(text1.getText().toString()));
                NavHostFragment.findNavController(FirstFragment.this)
                       .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    interface SendMessage {
        void sendData(int number);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        try {
            SM = (SendMessage) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException("Error in retrieving data. Please try again");
        }
    }

}

第二個片段:

public class SecondFragment extends Fragment {

    private FragmentSecondBinding binding;
    TextView textView;

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

        binding = FragmentSecondBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        textView = view.findViewById(R.id.score_result);

        binding.buttonSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(SecondFragment.this).navigate(R.id.action_SecondFragment_to_FirstFragment);
            }
        });
    }

    protected void displayReceivedData(int number)
    {
        textView.setText(number);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

查看尋呼機適配器:

public class ViewPagerAdapter extends FragmentStateAdapter {
    public ViewPagerAdapter(FragmentManager fm, Lifecycle behavior) {
        super(fm,behavior);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        Fragment fragment = null;
        if (position == 0) {
            fragment = new FirstFragment();
        } else if (position == 1) {
            fragment = new SecondFragment();
        }
        assert fragment != null;
        return fragment;
    }

    @Override
    public int getItemCount() {
        return 2;
    }
}

主要活動:

public class MainActivity extends AppCompatActivity implements FirstFragment.SendMessage{

    ViewPager2 viewPager;
    ViewPagerAdapter viewPagerAdapter;
    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);

        viewPager = findViewById(R.id.viewPager2);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),getLifecycle());
        viewPager.setAdapter(viewPagerAdapter);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    }

    @Override
    public void sendData(int number) {
        SecondFragment secondFragment=new SecondFragment();
        SecondFragment f = (SecondFragment) getSupportFragmentManager().findFragmentByTag(String.valueOf(secondFragment));
        f.displayReceivedData(number);
    }

    @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_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_status) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

有很多方法可以在片段之間傳遞數據,特別是對於導航組件,我們有一種叫做 SafeArgs 的東西。 使用下面的鏈接來考慮您希望嘗試哪種方法,android 文檔對此不言自明。

https://developer.android.com/guide/navigation/navigation-pass-data

另外,由於您特別詢問是否可以捆綁銷售,所以是的。

 // FirstFragment.class Bundle bundle = new Bundle(); bundle.putString("data", text1.getText().toString()); NavHostFragment.findNavController(FirstFragment.this).navigate(R.id.action_FirstFragment_to_SecondFragment,bundle); // SecondFragment.class TextView textView = view.findViewById(R.id.score_result); textView.setText(getArguments().getString("data"));

暫無
暫無

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

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