一个快速的选择(不确定这是否安全或推荐)是在您的项目中创建一个具有存储信息所需的属性的类,并在 MainActivity 中实例化此类的对象。然后,从片段中引用它,并在文本被更改或引入片段的 EditText 时填写您需要保存的数据(例如在属性 EditText1Data 或其他内容中)。然后只需将您填充有片段信息的对象中包含的数据存储到数据库中。在这个被调用类的构造函数中为属性放置一些默认值,以避免空值问题。这可以帮助您轻松地双向传输数据 Activity<-->Fragments ,即使这可能意味着您必须非常小心,因为您可能会遇到空指针异常。
//这是你的DataClass,用来在Activity和Fragment之间传输数据。
public class DataClass {
public String EditText1Value;
public String EditText2Value;
public DataManager()
{
EditText1Value="Default Text";
EditText2Value="Default Text";
}
}
//这是MainActivityClass
public class MainActivity extends Activity{
//instance of the DataClass to be passed to fragments with the method getDataClass
public DataClass dataClass = new DataClass();
//Main Activity code goes here...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
}
//This method returns a reference to the DataClass Object
public DataClass getDataClass()
{
//Return this class instance object of the DataClass class
return (dataClass);
}
//Now this is the method to push data to DB, called whenever an activity button is pressed.
private boolean WriteToDB ()
{
//Suppose this receives a String
WritetoDB(dataClass.EditText1Value);
}
}
//而这是通过DataClass对象发送数据的Fragment
public class ExampleFragment extends Fragment {
//Used to reference MainActivityObject and store info
DataClass dataClass;
//Used to Reference Activity's EditTexts
private EditText editText1;
//TextWatcher used to detect the EditText Field Changes
private TextWatcher EditText1_Txtwtr;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.whatever_layout, container, false);
editText1= (EditText)v.findViewById(R.id.idEditText1);
setHasOptionsMenu(true);
return v;
}
@Override
public void onResume ()
{
super.onResume();
//code...
//Get MainActivity's DataClass object reference.
dataClass= ((MainActivity)getActivity()).getDataClass();
//store info whenever you need to, not necessarily on each keystroke, and store it in the object, not in the DB
dataClass.EditText1Value = editText1.getText().toString();
// Also, to capture whenever a edittext changes, you can use a textwatcher.
EditText1_Txtwtr= new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3)
{}
@Override
public void afterTextChanged(Editable editable)
{}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3)
{
dataClass.EditText1Value = editText1.getText().toString();
}
}
//Asign TextWatcher to your Edit Text.
editText1.addTextChangedListener(EditText1_Txtwtr);
}
}