当任何人按下按钮,片段时,我会尝试制作警告对话框。我尝试了几种方式,但我无法做到。有没有办法在片段内做到这一点。
package com.topicsfeedback.www.mypackage.activity;
/**
* Created by hasib on 2/22/2016.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.topicsfeedback.www.mypackage.R;
import java.net.Inet4Address;
public class MessagesFragment extends Fragment {
public MessagesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View vv = inflater.inflate(R.layout.fragment_messages, container, false);
return vv;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
// Back button press start
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit This Apps")
.setMessage("Do You want to exit?")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent myinnn = new Intent(getActivity(), HomeFragment.class);
startActivity(myinnn);
}
})
.setNegativeButton("NO", null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event); //Here onKeyDown can't resolve
}
}
//Backbutton press end
@Override
public void onDetach() {
super.onDetach();
}
}
答案 0 :(得分:1)
要按回按钮的回调,您需要在活动中覆盖此方法:
@Override
public void onBackPressed() {
super.onBackPressed();
// Your code here
}