无法从片段中的edittext获取值

时间:2016-03-27 17:45:35

标签: java android android-fragments android-edittext

我是新来的...

我的问题是:如何从片段中获取edittext中的数据?我真的尝试过我一直在寻求的一切,但没有结果。

以下是代码:

  

XML文件

register_user.xml

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <include layout="@layout/toolbar"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/secondary_dark"
        app:tabMode="fixed"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

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

fragment_pdata.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.fundacioncanihua.inutritionist.rnp.Fragments.PersonalDataFragment">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pData"
    android:layout_marginTop="10dp"
    android:textSize="40dp"
    android:textStyle="bold"
    android:id="@+id/textView"/>

<android.support.design.widget.TextInputLayout
    android:id="@+id/flayout_lastname"
    android:theme="@style/TextLabel"
    android:layout_below="@+id/textView"
    android:layout_marginTop="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/input_lName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/lName"
        android:inputType="text"
        android:maxLength="25"
        android:drawableLeft="@drawable/ic_edittext_user"
        android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/flayout_firstname"
    android:theme="@style/TextLabel"
    android:layout_below="@+id/flayout_lastname"
    android:layout_marginTop="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/input_fName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/fName"
        android:inputType="text|textCapWords"
        android:maxLength="25"
        android:drawableLeft="@drawable/ic_edittext_user"
        android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>

<LinearLayout android:layout_width="match_parent"
    android:id="@+id/fHorizontal"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_below="@id/flayout_firstname"
    android:layout_marginTop="10dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/flayout_birthday"
        android:theme="@style/TextLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/input_birthday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/birthday"
            android:inputType="date"
            android:drawableLeft="@drawable/ic_edittext_bd"
            android:drawablePadding="20dp"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/flayout_gender"
        android:theme="@style/TextLabel"
        android:layout_width="150dp"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/input_gender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/gender"
            android:inputType="text|textCapSentences"
            android:maxLength="1"
            android:drawableLeft="@drawable/ic_edittext_gender"
            android:drawablePadding="20dp"/>
    </android.support.design.widget.TextInputLayout>
</LinearLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/flayout_location"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/TextLabel"
    android:layout_below="@id/fHorizontal"
    android:layout_marginTop="10dp">

    <EditText
        android:id="@+id/input_location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/location"
        android:inputType="text|textCapWords"
        android:maxLength="25"
        android:drawableLeft="@drawable/ic_edittext_location"
        android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>

  

Java类

注册患者

public class RegisterPatient extends AppCompatActivity implements PersonalDataFragment.getEditText {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.ic_tab_data,
        R.drawable.ic_tab_measures,
        R.drawable.ic_tab_clinical
};
String s_lname;

private ConnectionSQL dataBase;

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

    dataBase = new ConnectionSQL(getApplicationContext());

    //Setting up the toolbar
    Toolbar toolBar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolBar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case R.id.action_settings:
            //Code
            break;
        case R.id.regbutton:
            registerPatient();
            break;
    }
    return super.onOptionsItemSelected(item);
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new PersonalDataFragment(), getString(R.string.pData));
    adapter.addFragment(new AnthropometryFragment(), getString(R.string.anthro));
    adapter.addFragment(new NutritionalClinicalFragment(), getString(R.string.nutcli));
    viewPager.setAdapter(adapter);
}

private void registerPatient() {

    try {

        /*final String s_lName = i_lName.getText().toString();
        final String s_fName = i_fName.getText().toString();
        final String s_bday = i_bday.getText().toString();
        final String s_gender = i_gender.getText().toString();
        final String s_location = i_location.getText().toString();

        dataBase.addPatient(s_lName, s_fName, s_bday, s_gender, s_location);*/

        Toast.makeText(RegisterPatient.this, "Patient added successfully!", Toast.LENGTH_SHORT).show();
        clearForm((ViewGroup) findViewById(R.id.registerlayout));
    } catch (Exception e) {
        Toast.makeText(RegisterPatient.this, "Something were wrong! Try it again.", Toast.LENGTH_SHORT).show();
        Log.w("WARNING", e.getMessage());
        Log.w("WARNING_INFO", e.getCause());
    }

}

private void clearForm(ViewGroup group)
{
    for (int i = 0, count = group.getChildCount(); i < count; ++i) {
        View view = group.getChildAt(i);
        if (view instanceof EditText) {
            ((EditText)view).setText("");
        }

        if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
            clearForm((ViewGroup)view);
    }
}

@Override
public void onFragmentEditTextChanged(String lname) {

}

}

PersonalDataFragment.java 公共类PersonalDataFragment扩展Fragment {

public EditText editText;
public Calendar myCalendar;
public DatePickerDialog.OnDateSetListener uDate;
private getEditText listener = null;

public PersonalDataFragment() {
    // Required empty public constructor
}

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

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

    View v = inflater.inflate(R.layout.fragment_pdata, null);

    //Calendar
    editText = (EditText) v.findViewById(R.id.input_birthday);
    final EditText i_lname = (EditText) v.findViewById(R.id.input_lName);
    editText.setTextIsSelectable(true);

    myCalendar = Calendar.getInstance();

    uDate = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }

    };

    editText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View vi) {
            // TODO Auto-generated method stub
            new DatePickerDialog(getActivity(), uDate, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    //Getting EditTexts
    i_lname.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {  }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {  }

        @Override
        public void afterTextChanged(Editable s) {
            if (listener != null) {
                final String stg = i_lname.getText().toString();
                listener.onFragmentEditTextChanged(stg);
                Toast.makeText(getActivity(), stg, Toast.LENGTH_SHORT).show();
            }
        }
    });
    return v;
}

@Override
public void onAttach(Context context) {
    listener = (getEditText) context;
}

private void updateLabel() {
    String myFormat = "dd/MM/yy";
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

    editText.setText(sdf.format(myCalendar.getTime()));
}

public interface getEditText {
    public void onFragmentEditTextChanged(String lname);
}

}

我不知道我做错了什么。我需要访问这些EditText才能使用它们并将用户添加到SQLite DB中,但由于EditText位于Fragment中,我无法直接从RegisterUser类访问它们。

关于如何解决这个问题的任何想法?我将非常感激。

提前致谢。

1 个答案:

答案 0 :(得分:1)

尝试这样做,

TextInputLayout FlayoutBirthday= (TextInputLayout) v.findViewById(R.id.flayout_birthday);
EditText i_lname = FlayoutBirthday.getEditText();