android開發之長按彈出貼上,點選之後複製
阿新 • • 發佈:2019-02-10
設定一個長按點選事件,然後呼叫下面方法
private void ShowPopWindow(int x, int y) {
popupWindow = new PopupWindow(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(CommentCircleShareActivity.this);
tv.setText("貼上");
tv.setTextColor(getResources().getColor(R.color.white));
tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_corners));
tv.setPadding(10, 10, 10, 10);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClipboardManager copy = (ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
int index = mEditTextContent.getSelectionStart();//獲取游標所在位置
if (copy == null || TextUtils.isEmpty(copy.getText())){
return;
}
String text= copy.getText().toString();
Editable edit = mEditTextContent.getEditableText();//獲取EditText的文字
if (index < 0 || index >= edit.length() ){
edit.append(text);
}else{
edit.insert(index,text);//游標所在位置插入文字
}
mEditTextContent.setSelection(mEditTextContent.getText().length());
popupWindow.dismiss();
}
});
popupWindow.setContentView(tv);
popupWindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);// 設定選單的寬度
popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
popupWindow.setFocusable(true);// 獲取焦點
popupWindow.setTouchable(true); // 設定PopupWindow可觸控
popupWindow.setOutsideTouchable(true); // 設定非PopupWindow區域可觸控
//設定點選隱藏popwindow
ColorDrawable dw = new ColorDrawable(0x00000000);
popupWindow.setBackgroundDrawable(dw);
popupWindow.showAtLocation(mLayoutComment, Gravity.NO_GRAVITY, x, y);
}