Android 用PopupWindow實現載入等待介面
阿新 • • 發佈:2019-02-05
實現載入等待介面我用了兩種方式,一種是用PopupWindow實現,另一種便是用Activity實現。用Activity實現方法請見我的另一篇部落格:
首先看效果:
用PopupWindow實現此功能還是比較簡單的,首先我們寫一個佈局,只有一個登入按鈕,用於觸發等待介面:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop ="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.toprs.myapplication.MainActivity">
<Button
android:text="登入"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="loginClick"
android:id ="@+id/button2"/>
</LinearLayout>
然後為登入按鈕新增監聽事件:
package com.wang.myapplication;
import ...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loginClick(View v){
final PopupWindow popupWindow = new PopupWindow();
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setFocusable(true);
View view = LayoutInflater.from(this).inflate(R.layout.popup,null);
popupWindow.setContentView(view);
popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER,0,0);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "登入成功", Toast.LENGTH_SHORT).show();
popupWindow.dismiss();
}
},2000);
}
}
其中彈出的PopupWindow需要一個佈局,也就是簡單放入一個ProgressBar:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="200dp">
<ProgressBar
android:id="@+id/progressBar4"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
大功告成,執行一下即可!!