单击按钮时,我想从扩展 Fragment 的 PlaceHodler 类中显示一个弹出窗口。为了测试,我编写了这段代码,它确实有效,但我想这很荒谬(使用 Button 对象作为父视图等等......我找不到另一种让它工作的方法......)。请查看此代码并建议我如何改进它。请不要评判我,因为我是编程的初学者。
我的代码:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final Button button1 = (Button)rootView.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Log.i("ilog", "onClick() works");
PopupWindow pw = new PopupWindow(getActivity());
TextView tv = new TextView(getActivity());
LayoutParams linearparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(linearparams1);
tv.setText("Testing");
pw.setContentView(tv);
pw.setWidth(400);
pw.setHeight(180);
pw.showAtLocation(button1, Gravity.CENTER_HORIZONTAL, 25, 25);
pw.update();
}
});
return rootView;
}
}