سؤال

أنا غير قادر على عرض كل من setContentView (r.layout.main) وعرض معًا. أعتقد أنني لا أحصل على المفهوم بشكل صحيح. هل يمكن لأي شخص أن يشرح لي أين أخطئ. شكرًا لك. // يرجى قراءة التعليق في الكود

أحاول عرض صورة على main.xml باستخدام bitmapfactory.

   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 هو

هل كانت مفيدة؟

المحلول

عندما تتصل 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"

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top