原著如下
问 题
Basically, I have a TextView in a layout which I use for a PopupWindow. I show this PopupWindow when a user clicks a button; I want to be able to dynamically change the text in the PopupWindow upon button click. However, findViewById(my_textview).setText() does not seem to do anything, and indeed causes the PopupWindow to no longer show when I click the button.
I can set text from the layout xml fine.
Anyone know what's up with this? Thanks-
基本上,我有,我用了一个PopupWindow布局一个TextView。我表明,当用户点击一个按钮,这个PopupWindow;我希望能够在点击按钮来动态更改PopupWindow文本。然而,findViewById(my_textview).setText()似乎并没有做任何事情,确实会导致PopupWindow当我按一下按钮不再显示。
我可以设置从布局XML精细的文本。
任何人都知道什么是这个吗?谢谢 -
I solved the problem. For whatever reason you need to call popup.getContentView().findViewById instead of just findViewById (where popup is your PopupWindow object). I wasn't getting a NullPointerException before so I'm not exactly sure why this fixed the issue but it did.
So the code goes something like:
我解决了这个问题。不管什么原因,你需要调用popup.getContentView()。findViewById,而不是仅仅findViewById(其中弹出你PopupWindow对象)。我没有得到一个NullPointerException异常之前,所以我不知道是什么原因这个固定的问题,但它没有。
所以,code是这样:
PopupWindow pw = new PopupWindow(your layout and params here);
((TextView)pw.getContentView().findViewById(R.id.my_textview)).setText("hello there");
pw.showAtLocation(your params here);
我都代码实现:
//PopupWindow具体实现
dateSectionView = View.inflate(this,R.layout.pop_xxx,null);//布局
//创建PopupWindow
popDateView = new PopupWindow(dateSectionView, AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT, true);
/******此处重点********/
tv_StartDate = popDateView.getContentView().findViewById(R.id.tv_startDate);
tv_EndDate = popDateView.getContentView().findViewById(R.id.tv_endDate);
/******此处重点********/
//设置显示日期
String start = null;
if (startDate == null){
start = sale_list_datetime;
}else {
start = startDate;
}
String end = null;
if (endDate == null){
end = sale_list_datetime;
}else {
end = endDate;
}
tv_StartDate.setText(start);
tv_EndDate.setText(end);
tv_StartDate.setOnClickListener(new StartDateClick());
tv_EndDate.setOnClickListener(new EndDateClick());
// 在PopupWindow里面就加上下面代码,让键盘弹出时,不会挡住pop窗口。
popDateView.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
popDateView.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
popDateView.setBackgroundDrawable(new BitmapDrawable());
popDateView.setOutsideTouchable(true);
if (Build.VERSION.SDK_INT >= 24) {
Rect visibleFrame = new Rect();
lin_choosetime.getGlobalVisibleRect(visibleFrame);
int height = (lin_choosetime.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom)/5;//高度全屏高度的1/5
popDateView.setHeight(height);
popDateView.showAsDropDown(lin_choosetime, 0, 0);
} else {
popDateView.showAsDropDown(lin_choosetime, 0, 0);
}
popDateView.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));