本文共 3128 字,大约阅读时间需要 10 分钟。
继承RelativeLayout,然后向其中添加各种状态的View,通过对各种View的显示隐藏的切换来实现各种状态的切换。
public class LoadingLayout extends RelativeLayout {public LoadingLayout(Context context) { this(context,null);}public LoadingLayout(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0);}public LoadingLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr);}
}
private View LoadingView,SuccessView,FaildView;private ArrayListviews;public void setStatusView(View loadingView, View successView, View faildView){ if(views==null){ views=new ArrayList<>(); }else if(views.size()>0){ views.clear(); } if(getChildCount()>0){ removeAllViews(); } LoadingView=loadingView; SuccessView=successView; FaildView=faildView; LoadingView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); SuccessView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); FaildView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); addView(LoadingView); addView(SuccessView); addView(FaildView); views.add(LoadingView); views.add(SuccessView); views.add(FaildView);}
private void HideViews(){ if(views!=null&&views.size()>0){ for(View v:views){ v.setVisibility(GONE); } }}
public void setStatus(LoadingType loadingType){ //在设置之前先将所有View隐藏 HideViews(); switch (loadingType){ case LOADING: if(LoadingView!=null){ LoadingView.setVisibility(VISIBLE); } break; case SUCCESS: if(SuccessView!=null){ SuccessView.setVisibility(VISIBLE); } break; case FAILD: if(FaildView!=null){ FaildView.setVisibility(VISIBLE); } break; }}public enum LoadingType{ LOADING,SUCCESS,FAILD}
public class MainActivity extends AppCompatActivity {private LoadingLayout mLoadingLayout;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLoadingLayout=findViewById(R.id.myloadlayout); //添加状态View mLoadingLayout.setStatusView(View.inflate(this,R.layout.view_loading,null),View.inflate(this,R.layout.view_success,null),View.inflate(this,R.layout.view_faild,null));}public void onClick(View view){ switch (view.getId()){ case R.id.bt_loading: mLoadingLayout.setStatus(LoadingLayout.LoadingType.LOADING); break; case R.id.bt_success: mLoadingLayout.setStatus(LoadingLayout.LoadingType.SUCCESS); break; case R.id.bt_faild: mLoadingLayout.setStatus(LoadingLayout.LoadingType.FAILD); break; }}}
转载地址:http://ohdul.baihongyu.com/