您的位置:首页 > 移动开发 > Android开发

Android popwindow简单实现弹框

2017-10-26 08:46 274 查看
     简单实现点击弹出消息框(popwindow)

     先看案例



    点击结算弹出,作出相应处理,当点击弹框以外,弹框自动消失

    直接上代码

1:main.xml(就一个按钮)

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="立即支付"
android:textSize="30dp"
android:background="#f00"
android:layout_centerInParent="true"
android:id="@+id/tv"
/>

2:popwindow布局

<TextView
android:id="@+id/pop_computer"
android:layout_margin="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="创建订单"/>
<TextView
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#fff"
/>
<TextView
android:layout_margin="20dp"
android:id="@+id/pop_financial"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="立即支付"/>

3:Activity.class

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private TextView tv;
private PopupWindow mPopWindow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showPopupWindow();
}
});
}
private void showPopupWindow() {
//设置contentView
View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuplayout, null);
mPopWindow = new PopupWindow(contentView,
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
mPopWindow.setContentView(contentView);
//设置各个控件的点击响应
TextView tv1 = (TextView)contentView.findViewById(R.id.pop_computer);
TextView tv2 = (TextView)contentView.findViewById(R.id.pop_financial);
tv1.setOnClickListener(this);
tv2.setOnClickListener(this);
//当点击popwindow以外的地方关闭窗口
mPopWindow.setBackgroundDrawable(new BitmapDrawable());
mPopWindow.setOutsideTouchable(true);
View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
//显示的位置
mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 200, 300);

}

@Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.pop_computer:{
// 点击事件
mPopWindow.dismiss();//关闭窗口
}
break;
case R.id.pop_financial:{
// 点击事件
mPopWindow.dismiss();//关闭窗口
}
}
}
}

注释还算全,慢慢看。

这样一个简单的popwindow就实现了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: