需求:进入activity中,发起网络请求,在请求成功获取数据后,显示activity,隐藏加载页面;如果请求不成功,则一直显示加载页。
方案:最通俗易懂的是在跟布局加一个全屏View,请求成功后隐藏就可以。但是这样的话每个页面都得修改布局比较麻烦,
所以现在用动态代码方案,封装成一个方法,每次调用便可。
代码如下:
布局:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/j"> <TextView android:layout_width="match_parent" android:layout_height="160dp" android:background="@color/b" android:gravity="center" android:text=""/> </RelativeLayout>
加载页布局:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#F9000000" > <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> <TextView android:id="@+id/t1" android:layout_width="100dp" android:layout_height="100dp" android:layout_centerHorizontal="true" android:layout_marginTop="120dp" android:background="@color/b" android:gravity="center" android:text="1"/> </RelativeLayout>
activity代码:
public class EFBActivity extends AppCompatActivity { private Context mContext; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); // mView.setVisibility(View.GONE); } }; View mView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.e_fb); mContext = this; mView = createV(EFBActivity.this); //模拟数据加载成功后 操作 mHandler.sendEmptyMessageDelayed(1, 3000); } /** * 动态创建ProgressBar * * @param a * @return */ public View createV(Activity a) { // 1.找到activity根部的ViewGroup,类型都为FrameLayout。 FrameLayout rootContainer = (FrameLayout) a.findViewById(android.R.id.content);//固定写法,返回根视图 // 2.初始化控件显示的位置 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT); lp.gravity = Gravity.CENTER; // 3.设置控件显示位置 final View view = View.inflate(mContext, R.layout.e_fb_dialog, null); TextView t1 = (TextView) view.findViewById(R.id.t1); t1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //设置点击 后隐藏加载页 view.setVisibility(View.GONE); } }); view.setVisibility(View.VISIBLE); // 4.将控件加到根节点下 rootContainer.addView(view); return view; } }