一、布局的代码:
<TextView
android:id="@+id/textViews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/networktrue"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttons"
android:layout_below="@id/textViews"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="@string/ifnetwork"
/>
二、布局的效果图
三、点击“是否有网络这个按钮”可以测试到当前网络是否正常,如下这个是实现这个验证是否有网络的代码
public class Test implements OnClickListener{
private Context context;
private TextView tv;
private ConnectivityManager cm;//这个是用来封装连接网络
public Test(Context context){
this.context = context;
}
@Override
public void onClick(View v) {
Activity c = (Activity)context;
//关联到这个提示控件
tv = (TextView) c.findViewById(R.id.textViews);
String netStatus;//这个是用来封装网络是否正常
int color;//这个是用来封装色体
cm = (ConnectivityManager) c.getSystemService(c.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo==null){
//提示没有网络
netStatus = c.getResources().getString(R.string.netStatus0);
color = c.getResources().getColor(R.color.red);
}else{
//不需提示
netStatus = c.getResources().getString(R.string.netStatus1);
color = c.getResources().getColor(R.color.green);
}
tv.setText( netStatus );
tv.setBackgroundColor(color);
}
}
---------------------------------------------------------------------------------
public class MainActivity extends Activity {
private Button tstNetwrkBt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
/*tstNetwrkBtn = (Button) findViewById(R.id.tstNetwrkBtn);
tstNetwrkBtn.setOnClickListener( new Btn1Listener(this) );*/
tstNetwrkBt = (Button) findViewById(R.id.buttons);
tstNetwrkBt.setOnClickListener( new Test(this));
}