0

I know how to check for internet connection, In many activities and fragments you would change your layout to a static view which indicates there is no internet connection.
I want to make my code a bit more dynamic.
The question is: how do you change your contentView based on internet connection?
I can think of checking if internet is availbale on every Activity and if it's not, simply change view and override onClickListener but I don't want to repeat myself.

Mehrdad Shokri
  • 1,974
  • 2
  • 29
  • 45

1 Answers1

0

Write code something like this ,

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

/**
 * @author Krish
 */
public abstract class BaseActivity extends FragmentActivity {

    protected abstract int getLayoutId();

    private LinearLayout connectivtyStateView;
    private ViewGroup content;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FrameLayout conainer = new FrameLayout(this);
        conainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        this.connectivtyStateView = new LinearLayout(this);
        this.connectivtyStateView.setBackgroundResource(R.color.abc);
        this.connectivtyStateView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        conainer.addView(connectivtyStateView);
        this.content = (ViewGroup) LayoutInflater.from(this).inflate(getLayoutId(), conainer, true);
        setContentView(conainer);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //registerReceiver()
    }


    @Override
    protected void onPause() {
        super.onPause();
        // unregisterReceiver();
    }


    /** Callback for connection change */
    private void handleConnectivityChange(boolean isConnected) {
        if (isConnected) {
            connectivtyStateView.setVisibility(View.GONE);
            content.setVisibility(View.VISIBLE);
        } else {
            connectivtyStateView.setVisibility(View.VISIBLE);
            content.setVisibility(View.GONE);
        }
    }

}

And extend this class for your Activities , and implement the abstract method for returning the layout resource id for your content layout.

Krish
  • 3,860
  • 1
  • 19
  • 32