如何将回调添加到在片段中创建的活动?

时间:2015-04-26 11:17:29

标签: android android-intent android-fragments android-activity

我有一个带有按钮的片段,在单击/按下时会调用以下方法:

public void onClick() {
   Intent intent = new Intent(getActivity(), MyNewActivity.class);
   startActivity(intent)
}

但是,我想将回调方法传递给在活动的MyNewActivity方法内调用的onDestroy。我需要回调方法来调用我的片段的finish()方法。

我尝试使用静态变量并且它有效,但这似乎是一个糟糕的设计。最好的方法是什么?如果不是通过回调方法,那么更好的方法是什么?

1 个答案:

答案 0 :(得分:0)

使用评论中建议的public class MyFragment extends Fragment { private static final int REQUEST_CODE = 1353; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment, container, false); v.findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), SecondActivity.class); startActivityForResult(intent, REQUEST_CODE); } }); return v; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE) { Toast.makeText(getActivity(), "Hooray! Fragment got result from activity!", Toast.LENGTH_SHORT).show(); } } }

使用以下代码:

片段:

public class SecondActivity extends Activity {

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

        findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                setResult(Activity.RESULT_OK);
                finish();
            }
        });
    }
}

第二项活动:

JSONObject data;
String message = "Hey pal" + ", it looks like " + cur_user.get("realName") + " added you to the list '" + list_name + "'. press on me to check it.";
ParsePush push = new ParsePush();

try {
    data = new JSONObject();   
    data.put("alert", message);
    data.put("test", "test");

    push.setQuery(query);                    
    push.setData(data);
} catch (JSONException e1) {
    e1.printStackTrace();
} finally {
   push.sendInBackground();
}