Android - 如何在从Fragment扩展的类中使用Toast,AlertDialog ....

时间:2015-05-24 13:32:51

标签: java android android-fragments android-fragmentactivity

我需要在扩展Toast的类中使用AlertDialogFragment和其他人。我怎么了?

public class TelaCONTATO extends Fragment{
Activity activity = getActivity();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.telacontato, container,false);        

    return rootView;
}
public void clique(View v){
    Toast.makeText(getActivity(), "Cliquei", Toast.LENGTH_LONG).show();
}

}

2 个答案:

答案 0 :(得分:2)

如果由于某种原因您无法通过getActivity获取该应用程序的上下文,则可以使用该应用程序的上下文:

Toast.makeText(getApplicationContext(), "Cliquei", Toast.LENGTH_LONG).show();

我注意到在片段实例化时你正在调用getActivity

Activity activity = getActivity();

这将始终导致activitynull,因为片段在实例化时尚未附加到Activity

答案 1 :(得分:1)

这是显示对话框和祝酒词的方式:

Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.my_layout);
dialog.show();


Toast toast = Toast.makeText(getActivity(), "Hello toast!", Toast.LENGTH_SHORT);
toast.show();