片段中是否有类似setResult()的方法?

时间:2016-04-08 09:15:29

标签: java android android-fragments

我正在使用片段。我在onResult()方法中收到错误。我需要setResult(RESULT_OK, data)的替代方法,我可以在我的片段中使用。请帮忙。

CalendarFragment:

package app.pal.study.samplestudy;

import android.app.Fragment;
import android.content .Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.Date;
import java.util.List;

public class CalendarFragment  extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_calendar, container, false);
    return rootView;
}


@Override
public void onResume() {
    super.onResume();
    refresh();
}

private void refresh() {
    CalendarEventDataSource dataSource = new CalendarEventDataSource(getActivity());
    dataSource.openReadOnlyDB();
    final List<CalendarEvent> calendarEvents = dataSource.getAllEvents();
    dataSource.close();
    CalAllEventsListAdapter adapter = new CalAllEventsListAdapter(calendarEvents);
    ListView listView = (ListView) getView().findViewById(R.id.all_event_list);
    listView.setAdapter(adapter);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        end();
        return true;
    }
    return super.onOptionsItemSelected(item);
}



public void onBackPressed() {
    end();
}

private void end() {
    Intent data = new Intent();
    data.putExtra(Constants.DATE_KEY, (Date)(getArguments().get(Constants.DATE_KEY)));
    setResult(RESULT_OK, data);
  }
}

3 个答案:

答案 0 :(得分:8)

如果你从另一个片段开始你的片段。

您需要使用:

/**
 * Optional target for this fragment.  This may be used, for example,
 * if this fragment is being started by another, and when done wants to
 * give a result back to the first.  The target set here is retained
 * across instances via {@link FragmentManager#putFragment
 * FragmentManager.putFragment()}.
 *
 * @param fragment The fragment that is the target of this one.
 * @param requestCode Optional request code, for convenience if you
 * are going to call back with {@link #onActivityResult(int, int, Intent)}.
 */

public void setTargetFragment(Fragment fragment, int requestCode) {
}

启动片段时。

像这样:

Fragment newFragment = new YourFragment();
newFragment .setTargetFragment(this, SOME_REQUEST_INT);

然后,在 YourFragment

Intent data = new Intent();
data.putExtra(Constants.DATE_KEY, (Date)(getArguments().get(Constants.DATE_KEY)));
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);

或者

getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, null);

答案 1 :(得分:1)

使用

getActivity().setResult(Activity.RESULT_OK, data);

答案 2 :(得分:1)

使用它可能会对你有所帮助..

getActivity().setResult(Activity.RESULT_OK, data);