2013-10-29 69 views
0

我想提出一個imageview的屏幕上,但。它給了「對象引用null」異常。我認爲我有一個邏輯錯誤。請幫我找到它。如何把ImageView的在移動應用[XAMARIN,ANDROID]

這裏是我的代碼:

我的佈局XML:

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">  
    <Button 
    android:id="@+id/button" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/changeImage"/> 
    <ImageView 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/sampleviewer" 
    android:src="@drawable/sampleimage"   
    android:scaleType="fitCenter"/> 

    </LinearLayout>   

在OnCreate中功能:

protected override void OnCreate (Bundle bundle) 
    { 
     base.OnCreate (bundle); 

     //Create the user interface in code 
     var layout = new LinearLayout (this); 
     layout.Orientation = Orientation.Vertical; 

     var aLabel = new TextView (this); 
     aLabel.Text = "Hello, Xamarin.Android"; 

     var aButton = new Button (this);  
     aButton.Text = "Say Hello"; 
     aButton.Click += (sender, e) => { 
      aLabel.Text = "Hello from the button"; 
     }; 

     var button = new Button (this); 
     button.Text = "AAAAAA"; 


     button.Click += delegate { 

      aLabel.Text = " PRESS THE BUTTON"; 
      var imageView = FindViewById<ImageView> (Resource.Id.sampleviewer); // After this line imageView variable is still null 
      imageView.SetImageResource (Resource.Drawable.sampleimage); 
     }; 

     layout.AddView (aLabel); 
     layout.AddView (aButton);   
     layout.AddView (button); 
     SetContentView (layout); 


    } 

回答

2

你在兩種不同的方式建立你的佈局在這裏。

  1. 您擁有一個包含ImageView一個XML佈局,但你永遠不引用XML佈局代碼的任何地方,因此Android從來沒有加載它(因此你不能訪問它)。
  2. 還通過創建一個新LinearLayout對象,並添加其他視圖創建它在Java代碼中的佈局。這種佈局有沒有ImageView

當你在這裏呼籲SetContentView()

SetContentView (layout); 

你告訴Android的使用您的代碼創建的佈局。如果你想使用XML佈局,可以更改爲:

SetContentView(Resource.Layout.Main); 

(與你的XML文件的實際名稱替換Main

否則,你需要添加ImageView你Java代碼。但是你可能不希望混搭使用Java代碼的佈局XML佈局。

另外請注意,您必須在調用FindViewById()之前調用SetContentView()

您可能還希望通過Xamarin的Resource Layouts教程閱讀。