我正在尝试从我的片段中以意图开始的活动中获取回调。
我认为我可以使用onActivityResult执行此操作,但是当我在finish();
活动时似乎没有调用它。这可能是片段吗?
Fragment.java
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Waiver");
myView = inflater.inflate(R.layout.waiver_layout, container, false);
signBtn = myView.findViewById(R.id.signBtn);
signBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SignatureActivity.class);
intent.putExtra("signatureAbleId", device.id);
intent.putExtra("signatureAbleType", "App\\Models\\Device");
startActivity(intent);
}
});
return myView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
Log.v("Activity", "The activity has finished");
if(resultCode == 200){
saveWaiver();
}
}
private void saveWaiver(){
Log.v("Save Waiver", "Saving waiver for you.");
}
SignatureActivity.java
public class SignatureActivity extends AppCompatActivity {
private Button btnClear;
private Button btnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_signature);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
signatureAbleId = bundle.getInt("signatureAbleId");
signatureAbleType = bundle.getString("signatureAbleType");
}
btnClear = findViewById(R.id.btnClear);
btnSave = findViewById(R.id.btnSave);
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSignaturePad.clear();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
setResult(200);
finish();
});
}
}
答案 0 :(得分:3)
使用它。它会帮助你
Intent intent = new Intent(getContext(), SignatureActivity.class);
而不是
Intent intent = new Intent(getActivity(), SignatureActivity.class);
是的,需要改变:
startActivity to startActivityForResult
答案 1 :(得分:1)
使用startActivityForResult
代替startActivity
startActivityForResult(intent, 11);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 11){
if(resultCode == 200){
saveWaiver();
}
}else{
super.onActivityResult(requestCode, resultCode, data)
}
}