我正在尝试向EditText
中的Fragment
添加验证,但我的应用程序崩溃了。我试图使用getActivity()
代替仍然面临同样问题的这个问题。
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.ValidationStyle;
public class TestFragment extends Fragment implements View.OnClickListener{
EditText ET_input_first_name, ET_input_last_name, ET_input_email, ET_input_contact, ET_comments;
String first_name, last_name, email , contact , comments;
private Button buttonSubmit;
private AwesomeValidation awesomeValidation;
public TestFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
view = inflater.inflate(R.layout.fragment_test, container, false);
ET_input_first_name = (EditText)view.findViewById(R.id.input_first_name);
ET_input_last_name = (EditText)view.findViewById(R.id.input_last_name);
ET_input_email = (EditText)view.findViewById(R.id.input_email);
ET_input_contact = (EditText)view.findViewById(R.id.input_contact);
ET_comments = (EditText)view.findViewById(R.id.comments);
awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);
buttonSubmit = (Button)view.findViewById(R.id.btn_test_drive);
//adding validation to edittexts
awesomeValidation.addValidation(this , R.id.input_first_name, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);
awesomeValidation.addValidation(this, R.id.input_last_name, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);
awesomeValidation.addValidation(this, R.id.input_email, Patterns.EMAIL_ADDRESS, R.string.nameerror);
awesomeValidation.addValidation(this, R.id.input_contact, "^[2-9]{2}[0-9]{8}$", R.string.nameerror);
buttonSubmit.setOnClickListener(this);
return view;
}
private void submitForm() {
if (awesomeValidation.validate()) {
Toast.makeText(getActivity(), "Validation Successfull", Toast.LENGTH_LONG).show();
}
}
@Override
public void onClick(View view) {
submitForm();
}
}
答案 0 :(得分:0)
要做到这一点,有两种方法:在片段
中使用此代码 1)EditText et = getActivity().findViewById(R.id.editText)
2)在您的活动中制作您的edittext public static
并仅在那里初始化它。然后在片段中使用只需编写YourActivity.edittext.getText().toString()
。它会起作用
答案 1 :(得分:-1)
awesomeValidation.addValidation(ET_input_first_name, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", "this is error message");
它完美地工作