我需要在扩展Toast
的类中使用AlertDialog
,Fragment
和其他人。我怎么了?
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();
}
}
答案 0 :(得分:2)
如果由于某种原因您无法通过getActivity
获取该应用程序的上下文,则可以使用该应用程序的上下文:
Toast.makeText(getApplicationContext(), "Cliquei", Toast.LENGTH_LONG).show();
我注意到在片段实例化时你正在调用getActivity
:
Activity activity = getActivity();
这将始终导致activity
为null
,因为片段在实例化时尚未附加到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();