仿微信好友添加提醒列表或者聊天列表长按弹出删除提示框
仿微信好友添加提醒列表或聊天列表长按弹出删除提示框
一、首先主页面有一个提示TextView和ListView,是用来放模拟数据的。
```java// MainActivity.javapublic class MainActivity extends AppCompatActivity {
private TextView mTvTitle;
private ListView mLvList;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTvTitle = findViewById(R.id.tv_title);
mLvList = findViewById(R.id.lv_list);
// 模拟数据 String[] data = {"好友1", "好友2", "好友3"};
ArrayAdapter
mLvList.setAdapter(adapter);
// 长按事件 mLvList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override public boolean onItemLongClick(AdapterView> parent, View view, int position, long id) {
// 弹出删除提示框 showDeleteDialog(position);
return true;
}
});
}
private void showDeleteDialog(int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("确认删除吗?");
builder.setMessage("您确定要删除好友" + mLvList.getItemAtPosition(position).toString() + "吗?");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
// 删除数据 mLvList.remove(position);
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
}
```
二、自定义Dialog```java// DeleteDialog.javapublic class DeleteDialog extends Dialog {
public DeleteDialog(Context context, int theme) {
super(context, theme);
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_delete);
// 获取控件 Button btnConfirm = findViewById(R.id.btn_confirm);
Button btnCancel = findViewById(R.id.btn_cancel);
// 设置点击事件 btnConfirm.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
// 删除数据 dismiss();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
// 取消删除 dismiss();
}
});
}
}
```
三、自定义ListView```java// MyListView.javapublic class MyListView extends ListView {
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 设置高度 setMeasuredDimension(widthMeasureSpec,200);
}
}
```
四、自定义Adapter```java// MyAdapter.javapublic class MyAdapter extends ArrayAdapter
public MyAdapter(Context context, int resource, List
super(context, resource, objects);
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
// 获取控件 TextView tv = (TextView) convertView;
if (tv == null) {
tv = new TextView(getContext());
}
tv.setText(getItem(position));
return tv;
}
}
```
五、主页面布局```xml
android:layout_height="match_parent"> android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="好友列表" /> android:layout_width="match_parent" android:layout_height="200dp" />
```
六、自定义Dialog布局```xml
android:layout_height="wrap_content">
```
以上就是仿微信好友添加提醒列表或聊天列表长按弹出删除提示框的实现步骤和代码。