2010-08-06 95 views
0

我無法同時顯示setContentView(R.layout.main)和View。我想我沒有理解這個概念。任何人都可以解釋我哪裏出錯了。謝謝。 //請閱讀代碼中的註釋main.xml隱藏視圖幫助

我想使用BitmapFactory在main.xml上顯示圖像。

public class TryGraph extends Activity 
{ 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main);//I think this is where I need your help 
    setContentView(new myView(this));//I want this to be displayed in main.xml 
} 

private class myView extends View{ 

    public myView(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     // TODO Auto-generated method stub 
     Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sinewave); 
     Bitmap resizedBitmap = Bitmap.createBitmap(myBitmap, 0, 0, 
       300, 143); 
     canvas.drawBitmap(resizedBitmap, 60, 50, null); 
     Paint myPaint = new Paint(); 
     myPaint.setColor(Color.RED); 
     myPaint.setStyle(Paint.Style.STROKE); 
     myPaint.setStrokeWidth(5); 
     canvas.drawRect(250,255,260,250, myPaint); 

    } 
} 

}

XML文件

回答

1

當你調用setContentView你告訴設備加載應顯示給用戶的整個佈局。在大多數情況下,這個視圖將佔據整個屏幕。現在這個佈局文件被認爲是根,並且可能包含子視圖,其中一個應該是您的ImageView。

<?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" 
    > 
<TextView 
    android:id="@+id/banner" 
    android:text="hello world" 
    > 
<ImageView 
    android:id="@+id/myImageView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/sampleimage" 
    /> 
<?LinearLayout> 

這ImageView的現在可以通過代碼通過使用findViewById(R.id.myImageView)訪問,然後你可以使用BitmapFactory來設置你的形象。如果圖像不會改變,您可以將其設置在佈局文件中android:src="@drawable/sampleimage"