我无法同时显示setContentView(R.layout.main)和View。我想我没有把这个概念弄好。任何人都可以解释我哪里出错了。谢谢。 //请阅读代码中的评论
我正在尝试使用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文件是
答案 0 :(得分: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>
现在可以使用findViewById(R.id.myImageView)
通过代码访问此ImageView,然后您可以使用BitmapFactory
设置图片。如果图像不会被更改,您只需在布局文件android:src="@drawable/sampleimage"