将EditText输入从活动移动到滑动视图的片段

时间:2017-07-07 06:04:43

标签: android android-fragments

这是发布时的MainActivity。用户输入一个数字,然后单击该按钮,Intent将他们带到他们输入的数字的滑动视图。

public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    continueButton = (Button) findViewById(R.id.ContinueButton);
    NumberET = (EditText) findViewById(R.id.etTotalAmount);
    continueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            number = NumberET.getText().toString();
            if (number.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("AMOUNT_KEY", number);
                FixedCosts fragment = new FixedCosts();
                fragment.setArguments(bundle);
                FragmentTransaction t = getSupportFragmentManager().beginTransaction();
                t.replace(R.id.container, fragment).commit();
                Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
            }
        }
    });
}

在片段中,我想设置textview的文本来显示该数字。我无法将此数字从此Activity类发送到Fragment。我该如何解决这个问题?

片段:

ublic class FixedCosts extends Fragment {
String amount;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fixed_costs_fragment, container, false);
    amount = this.getArguments().getString("AMOUNT_KEY");


    TextView TitletextView = (TextView) view.findViewById(R.id.amountTitle);
    TitletextView.setText(amount);
    return view;}}

以下是设置滑动视图的FragmentActivity:

public class FragmentActivity extends AppCompatActivity {
public static final String MY_CUSTOM_FRAGMENT_KEY = "I_GOT_THE_KEYS";

String MoneyAmount;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;


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

    /*MoneyAmount = getIntent().getExtras().getString("AmountMoney");*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}
private Fragment createCustomFragment(){
    Bundle bundle = new Bundle();
    bundle.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);

    PlaceholderFragment placeholderFragment = new PlaceholderFragment();
    placeholderFragment.setArguments(bundle);
    return placeholderFragment;
}


@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 true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item 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.
    int id = item.getItemId();

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

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber, String MoneyAmount) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        args.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Bundle bundle = getArguments();
        /*String amount = bundle.getString(MY_CUSTOM_FRAGMENT_KEY);
        TextView TitletextView = (TextView) FixedCosts.class.findViewById(R.id.amountTitle);
        TitletextView.setText(amount);*/

        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
       switch (position){
           case 0:
               FixedCosts fixedCosts = new FixedCosts();

               return fixedCosts;
       }
        return PlaceholderFragment.newInstance(position + 1, MoneyAmount);
    }
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Fixed Costs";
            case 1:
                return "Long term investments";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

}

2 个答案:

答案 0 :(得分:0)

删除continueButton.setOnClickListener侦听器中的活动开始代码,并在父活动的相同布局中添加view container,而不是在片段活动中:

public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    continueButton = (Button) findViewById(R.id.ContinueButton);
    NumberET = (EditText) findViewById(R.id.etTotalAmount);
    continueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            number = NumberET.getText().toString();
            if (amount.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("AMOUNT_KEY", number);
                FixedCosts fragment = new FixedCosts();
                fragment.setArguments(bundle);
                FragmentTransaction t = getSupportFragmentManager().beginTransaction();
                t.replace(R.id.container, fragment).commit();
            }
        }
    });
}

希望它会对你有所帮助。

答案 1 :(得分:0)

我通过将值保存到SharedPreferences来修复此问题 在MainActivity.class中:

SharedPreferences saveAmount = getSharedPreferences("MyPrefs", 0);
    final SharedPreferences.Editor editor = saveAmount.edit();
editor.putString("AMOUNT", amount);
                editor.commit();

在Fragment类中:

SharedPreferences sharedPrefs = this.getActivity().getSharedPreferences("MyPrefs", 0);

    String amount = (sharedPrefs.getString("AMOUNT", "Ummmmm"));