我知道这个问题可能会被问到其他人,但我无法找到适合我的解决方案。基本上我有fragment
一个按钮。当用户按下该按钮时,新的activity
被打开(该活动只扫描qr代码),我想将扫描结果传回我的fragment
。所以基本上
public class UiFragment extends Fragment implements ServiceCallBack {
// tons of code
scanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ScanActivity.class); // start scan activity
startActivity(intent);
}
});
}
public class ScanActivity extends AppCompatActivity {
// lots of code
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String result = scanResult.getContents();
if(result != null && result.length() > 0){
// now I want to go back to my previous fragment and pass result
}
}
finish();
}
}
请注意,我希望活动分段通信!我试图使用界面,但这对我没有用。有可能吗?
答案 0 :(得分:0)
如果我正确理解了您的问题,那么您必须有1个活动才能启动片段。我们将该活动命名为MainActivity
。
现在将UiFragment
更改为
public class UiFragment extends Fragment implements ServiceCallBack {
// tons of code
public static final SCAN_REQUEST_CODE = 1001; //Any number
scanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ScanActivity.class); // start scan activity
startActivityForResult(intent, SCAN_REQUEST_CODE);
}
});
}
您的MainActivity
将onActivityResult()
public class MainActivity extends AppCompatActivity {
// lots of code
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == UiFragment.SCAN_REQUEST_CODE){
//Check for result code if you want to
if(resultCode == RESULT_OK){
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String result = scanResult.getContents();
if(result != null && result.length() > 0){
//Now check if your fragment is visible
UiFragment uiFragment = (UiFragment) getSupportFragmentManager().findFragmentByTag(your_fragment_tag_name);
if (uiFragment != null && uiFragment.isAdded()) {
//Call your fragment's public method here. let's say you have a method update in your fragment then write
uiFragment.update(); // you can pass arguments in this method depending on your requirements.
}
}
}
}
}
}
}
您的ScanActivity
将没有onActivityResult()
方法
public class ScanActivity extends AppCompatActivity {
// lots of code
//Some method which scans and setResult
public void scan() {
setResult(RESULT_OK);
finish();
}
}