简体   繁体   中英

How getText() from EditText on tab fragment

I'm a new Android Developer and beginner on java programming. I'm developing a Carpool App but some problems have ocurred. I'm using a Tabbed Activity on 3 pages but just one is causing me trouble. I want to retrieve EditText data when i click on a Floating Action Button, but nothing is working.

Edit: Problem solved by adding PlaceholderFragment frag = (PlaceholderFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.containerNovo + ":" + mViewPager.getCurrentItem()); , where containerNovo is the id of my ViewPager mViewPager .

My Main XML file:

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/azul"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/PopupOverlay">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/azulclaro"/>

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/containerNovo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fabNovo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/check" />

My Main java code:

package petma.testesappcarona;

public class NovaCarona extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;
FloatingActionButton fab;

private ViewPager mViewPager;

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

    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.containerNovo);
    mViewPager.setAdapter(mSectionsPagerAdapter);

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

    fab = (FloatingActionButton) findViewById(R.id.fabNovo);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(NovaCarona.this, "input_nome.getText().toString()", Toast.LENGTH_SHORT).show();
        }
    });

}

Fragment Code:

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment implements View.OnClickListener {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    EditText input_nome,input_data, input_horario, input_saida, input_chegada, input_Recado;
    Spinner input_pessoas;
    SessionManager session;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_nova_carona, container, false);
        session = new SessionManager(getContext());
        session.checkLogin();
        input_data = (EditText)rootView.findViewById(R.id.input_data);
        assert input_data != null;
        input_data.setOnClickListener(this);

        input_horario = (EditText) rootView.findViewById(R.id.input_horario);
        assert input_horario != null;
        input_horario.setOnClickListener(this);

        input_chegada = (EditText)rootView.findViewById(R.id.input_chegada);
        input_saida = (EditText)rootView.findViewById(R.id.input_saida);
        input_nome = (EditText)rootView.findViewById(R.id.input_nome);
        input_pessoas = (Spinner)rootView.findViewById(R.id.input_pessoas);
        input_Recado = (EditText) rootView.findViewById(R.id.input_Recado);

        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        return rootView;
    }

    @Override
    public void onClick(View view) {
        if (view == input_data){
            int mYear, mMonth, mDay;
                // Get Current Date
                final Calendar c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);


                DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
                        new DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {

                                input_data.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);

                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
                datePickerDialog.show();
        }
        else if (view == input_horario){
            int mHour, mMinute;
            final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // Launch Time Picker Dialog
            TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(),
                    new TimePickerDialog.OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay,
                                              int minute) {
                            if(minute <= 9){
                                input_horario.setText(hourOfDay + ":"+"0"+minute);
                            }
                            else{
                                input_horario.setText(hourOfDay + ":" + minute);
                            }
                        }
                    }, mHour, mMinute, false);
            timePickerDialog.show();
        }
    }
}

I want to substitute the "input_nome.getText().toString()" part. I tried to use PlaceholderFragment but i don't know what is the ID of the fragment. I didn't find codes that people used PlaceholderFragment and Tabbed Activity.

You need to override the getItem() method of your tab adapter, to retrieve an instance of the fragment that is added in that tab so you can call a method from the fragment that retrieves you the text from the editText

public class TabAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> fragments = new ArrayList<>();
    private final List<String> fragmentsTitles = new ArrayList<>();
    private Context context;

    public TabAdapter (FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    .
    .
    .

}

adapter.getItem(position).getEditTextString();

Problem solved by adding: PlaceholderFragment frag = (PlaceholderFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.containerNovo + ":" + mViewPager.getCurrentItem()); , where containerNovo is the id of my ViewPager mViewPager. PlaceholderFragment frag = (PlaceholderFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.containerNovo + ":" + mViewPager.getCurrentItem()); , where containerNovo is the id of my ViewPager mViewPager. , where containerNovo is the id of my ViewPager mViewPager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM