布局作为活动中的条件状态打开

时间:2015-07-15 11:36:04

标签: android

我有两种布局。一个是在主要活动中显示我们是否有互联网连接。如果我们没有互联网连接,另一个也会在同一活动中显示。

我想在启动程序时有互联网连接,然后我会看到activity_main.xml布局。而且我想在启动程序时没有互联网连接,然后我会看到error.xml布局。

但是当我运行该程序时,它无法做到最好的描述。请不要对我说我不知道​​android的概念,请帮我解决这个问题。

public class MainActivity extends Activity {
    WebView webView;
    ImageView imageView1,imageView2,imageView3;
    Drawable drawable0,drawable1,drawable2;
    EditText editText;
    @Override
    protected void onCreate(Bundle s){

        if(isConnected()==false){
            super.onCreate(s);
            editText = (EditText) findViewById(R.id.textView);
            setContentView(R.layout.error);
        }
        else if(isConnected()==true){
super.onCreate(s);
            webView = (WebView) findViewById(R.id.webView);
            webView.setBackgroundColor(Color.rgb(88,255,114));
            imageView1 = (ImageView) findViewById(R.id.imageView);
            imageView2 = (ImageView) findViewById(R.id.imageView2);
            imageView3 = (ImageView) findViewById(R.id.imageView3);
            drawable0 = LoadImageFromWebOperations("http://127.0.0.1:8080/apps/image.jpg");
            drawable1 = LoadImageFromWebOperations("http://127.0.0.1:8080/apps/image2.jpg");
            drawable2 = LoadImageFromWebOperations("http://127.0.0.1:8080/apps/image4.jpg");
            imageView1.setImageDrawable(drawable0);
            imageView2.setImageDrawable(drawable1);
            imageView3.setImageDrawable(drawable2);
            setContentView(R.layout.activity_main);
        }
    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }

    private Drawable LoadImageFromWebOperations(String url)
    {
        try{
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is,"");
            return d;
        }catch (Exception e) {

            return null;
        }
    }}

1 个答案:

答案 0 :(得分:0)

您的代码失败是因为您在致电findViewById之前致电setContentView 。因此findViewById返回null,imageView1.setImageDrawable(drawable0);将返回NullPointerException

您还在主线程上进行网络操作(在LoadImageFromWebOperations(String url)中)。这是您的代码失败的另一个原因。