我正在尝试创建通用/基本表单,无论它是activity
还是fragment
。为简单起见,Form
可以这样提交:
class BaseFormActivity extends AppCompatActivity {
public abstract void submitForm();
@Override
public void setContentView(int layoutResID) {
ConstraintLayout activityBaseForm = (ConstraintLayout) getLayoutInflater().inflate(R.layout.activity_base_form, null);
FrameLayout frameBaseForm = activityBaseForm.findViewById(R.id.frame_base_form);
getLayoutInflater().inflate(layoutResID, frameBaseForm, true);
findViewById(R.id.btn_submit).setOnClickListener(v -> submitForm()) // for the sake of simplicity, there's a button that will trigger submitForm() method
super.setContentView(activityBaseForm);
}
}
在这里,我只包括一些表单的默认布局,以及一个用于触发抽象方法submitForm()
的提交按钮。但是,这仅适用于Android activities
。如何在不编写fragments
的情况下也可用于BaseFormFragment
?我不想重复从activity
到fragment
的默认行为,反之亦然。
答案 0 :(得分:0)
将其视为示例Presenter类,该类处理您的按钮单击并获取所有表单字段并发送到服务器
public class MyPresenter {
private MyPresenterIView iViewInstance;
public MyPresenter(MyPresenterIView iView){
this.iViewInstance=iView;
}
public void onSubmitClick(){
//write your logic here
String fieldOneText=iViewInstance.getFieldOneText();
sendToServer(fieldOneText);
}
private void sendToServer(String stringInfo){
//send info to server
}
}
MyPresenterIView界面
public interface MyPresenterIView{
String getFieldOneText();
}
并在“活动”或“片段”中使用Presenter
//implement MyPresenterIView to your Activity or Fragment
public class MyActivity extent SomeActivity implements MyPresenterIView{
private MyPresenter myPresenter;
//in onCreate or onCreateView(if its a fragment) initialize myPresenter
protected void onCreate(..){
myPresenter=new MyPresenter(this);//this will enforce Activity/Fragment to implement IView
}
@Override //comes from MyPresenterIView
public String getFieldOneText(){
return ((EditText)findViewById(R.id.edttext_field_one)).getText().toString().trim();
}
}