2016-05-24 8 views
2

それで、私のネットワーク接続をチェックして、真または偽の場合は実行してください。私はフラグメント内でシステムサービスを受ける前にゲイアクティブを使用することができますが、これは私のためには機能しません。助けてくれてありがとう:)ViewGroup Fragment内のネットワーク接続を確認する方法は?

public class Fragment1 extends Fragment implements View.OnClickListener { 

TextView textView; 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.frag1, container, false); 

ConnectivityManager connectivityManager =(ConnectivityManager).getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); 
     if(networkInfo!=null && networkInfo.isConnected()) 
     { 
      textView.setVisibility(View.INVISIBLE); 
     } 
     else 
     { 
      Byron.setEnabled(false); 
      Lennox.setEnabled(false); 
      Skenners.setEnabled(false); 
      Ballina.setEnabled(false); 
     } 

答えて

0

内部のViewGroupあなたはシステム・サービスを取得するためのgetContext()メソッドを使用することができます。

ConnectivityManager connectivityManager =(ConnectivityManager)getContext().getSystemService(Context.CONNECTIVITY_SERVICE); 
0

カスタムビュー/のViewGroupこのようなあなたのすべてのコンストラクタには、init()関数を追加することができます

public class CustomView extends Button { 
    public CustomView(Context context) { 
     super(context); 

     init(); 
    } 

    public CustomView(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     init(); 
    } 

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 

     init(); 
    } 

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 

     init(); 
    } 

    private void init() { 
     ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE); 
     // Other stuffs 
    } 
} 
0

はこのようにあなたのプロジェクトAppUtilで別のクラスを作成します。

public class AppUtil{ 
public static boolean isNetworkConnectionAvailable(Context ctx, boolean showDialog){ 
     ConnectivityManager manager =(ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetwork = manager.getActiveNetworkInfo(); 

     boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); 
     if(!isConnected&&showDialog){ 
      AppUtil.showSimpleDialog(ctx, ctx.getString(R.string.network_not_available), 
        ctx.getString(R.string.internet_not_available)); 
     } 
     return isConnected; 
    } 

} 

ネットワーク接続を確認するには、次のように進んでください:

public class Fragment1 extends Fragment implements View.OnClickListener { 

TextView textView; 

if (AppUtil.isNetworkConnectionAvailable(this, true)){ 
textView.setVisibility(View.INVISIBLE); 
} 
else{ 
Byron.setEnabled(false); 
      Lennox.setEnabled(false); 
      Skenners.setEnabled(false); 
      Ballina.setEnabled(false); 
} 


} 
関連する問題