我在我的MainActivity中使用了這種方法,我想在片段中的按鈕中使用這兩種方法,但我不知道如何將片段中的EditText
的數據發送到活動並使用按鈕。如何從EditText從片段獲取值到活動?
public void alta(View v) {
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this);
SQLiteDatabase bd = admin.getWritableDatabase();
String nome = et1.getText().toString();
String edad = et2.getText().toString();
String geno = et3.getText().toString();
String curp = et4.getText().toString();
ContentValues registro = new ContentValues();
registro.put("nombre", nome);
registro.put("edad", edad);
registro.put("genero", geno);
registro.put("curp", curp);
bd.insert("usuarios", null, registro);
bd.close();
et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
Toast.makeText(this, "Se cargaron los datos",
Toast.LENGTH_SHORT).show();
}
public void modificacion(View v) {
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this);
SQLiteDatabase bd = admin.getWritableDatabase();
String nome = et1.getText().toString();
String edad = et2.getText().toString();
String geno = et3.getText().toString();
String curp = et4.getText().toString();
ContentValues registro = new ContentValues();
registro.put("nombre", nome);
registro.put("edad", edad);
registro.put("genero", geno);
registro.put("curp", curp);
int cant = bd.update("usuarios", registro, "curp=" + curp, null);
bd.close();
if (cant == 1)
Toast.makeText(this, "se modificaron los datos", Toast.LENGTH_SHORT)
.show();
else
Toast.makeText(this, "no existe un usuario con ese nombre",
Toast.LENGTH_SHORT).show();
}
我有這樣的片段類,但我不知道如何通過EditTexts值。
public class Fragment1 extends Fragment {
EditText iet1,iet2,iet3,iet4;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
iet1 = (EditText) getActivity().findViewById(R.id.et1);
iet2 = (EditText) getActivity().findViewById(R.id.et2);
iet3 = (EditText) getActivity().findViewById(R.id.et3);
iet4 = (EditText) getActivity().findViewById(R.id.et4);
}
public Fragment1() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmento1, container, false);
return rootView;
}
}
我沒有使用SQLite而是從片段將數據發送到你可以創建一個共享數據的方法的接口的活動工作,實現您的活動內部的接口和實例化片段內從onViewCreate該接口和使用該方法在這裏發送數據一個很好的教程https://www.youtube.com/watch?v=VyyGP_d0Ia8 –
嘗試使用意圖檢查[This](http://stackoverflow.com/a/7325248/6747577) –