【发布时间】:2015-01-20 08:23:36
【问题描述】:
我正在片段 Tab3Fragment 中实现一个弹出窗口,并希望保留弹出窗口代码,
public void showPopup(View anchorView){
}
并尽可能地最小化 Tab3Fragment 中的其他地方以保持整洁。
目前 showPopup 看起来像这样,
public void showPopup(View anchorView) {
Button btnDismiss, btnFirstRecord, btnPreviousRecord, btnNextRecord, btnLastRecord;
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getSystemServi (Context.LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup_layout, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv = (TextView)popupView.findViewById(R.id.tv);
tv.setText("Blah, blah, blah");
btnDismiss = (Button)popupView.findViewById(R.id.btnDismissxml);
btnFirstRecord = (Button)popupView.findViewById(R.id.btnFirstRecordxml);
btnPreviousRecord = (Button)popupView.findViewById(R.id.btnPreviousRecordxml);
btnNextRecord = (Button)popupView.findViewById(R.id.btnNextRecordxml);
btnLastRecord = (Button)popupView.findViewById(R.id.btnLastRecordxml);
popupWindow.setFocusable(true);
int location[] = new int[2];
anchorView.getLocationOnScreen(location);
popupWindow.showAtLocation(anchorView, Gravity.CENTER, 0, 0);
}
}
问题: 有没有办法在 showPopup 中实现 onClick 方法 case-switch 语句来处理这个问题?也许像,
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnFirstRecordxml:
//firstRecord(v);
break;
case R.id.btnPreviousRecordxml:
//previousRecord(v);
break;
case R.id.btnNextRecordxml:
//nextRecord(v);
break;
case R.id.btnLastRecordxml:
//lastRecord(v);
break;
case R.id.btnDismissxml:
//closePopup(v);
break;
}}
其他解决方案比如把onClick放到popup_layout.xml中,
<Button
android:id="@+id/btnFirstRecordxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/pszFirstRecordButton"
android:onClick="Tab3Fragment.firstRecord"/>
处理按钮点击将不胜感激。提前谢谢...
2014 年 11 月 23 日更新。 这是一个适用于 showPopup() 中多个按钮代码的解决方案。我将在弹出窗口中有几个按钮....
private void showPopup(){
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup_layout, null);
Button btnDismiss=(Button)popupView.findViewById(R.id.btnDismissxml);
Button btnSaveRecord=(Button)popupView.findViewById(R.id.btnSaveRecordxml);
final PopupWindow popupWindow=new PopupWindow(popupView,480,500,true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 40);
//first button
btnSaveRecord.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
saveRecord();
}
});
//second button
btnDismiss.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}
});
}
有什么方法可以插入 case-switch 结构以允许 showPopup() 中的其他按钮代码?这将避免为每个按钮创建单独的 onClickListener-onClicks,如上所示。
【问题讨论】:
标签: android android-fragments popup onclicklistener buttonclick