【问题标题】:Get bitmap from assests then load it into the background从资产中获取位图,然后将其加载到后台
【发布时间】:2011-02-21 08:44:30
【问题描述】:

大家好,过去我在这里得到了很多帮助,想知道你们是否可以帮我解决一些问题。

我想从资产中加载位图,然后将其添加到我在代码中创建的线性布局图像视图的背景中。我知道如何使用 xml 布局文件执行此操作,但在这种情况下,我需要在代码中执行此操作。到目前为止,我有这个,它适用于 .xml 布局,但是当我尝试在代码中创建线性布局和 ImageView 时,图像没有显示出来。有什么我忽略或做错了。 这是我得到的代码

ImageView backgroundPainting = new ImageView(this);
    backgroundPainting.setAdjustViewBounds(true);


    LinearLayout rel = new LinearLayout(this);
//    RelativeLayout backgroundPaintingRL = (RelativeLayout) findViewById(R.id.RelativeLayout01);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.FILL_PARENT);
    //lp.addRule(RelativeLayout.BELOW, R.id.ButtonRecalculate);
    //lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    rel.addView(backgroundPainting, lp);


    // backgroundPainting = (ImageView) findViewById(R.id.backgroundPainting2);
     getArtist = levelSelect.getArtistNameSelected();
     getLevel = level.getLevelSelected() ;

     String imagePath = "artists-images/"+getArtist + getLevel+".jpg";
     try { // Get reference to AssetManager
         AssetManager mngr = getAssets();
         // Create an input stream to read from the asset folder
            InputStream ins = mngr.open(imagePath);

            // Convert the input stream into a bitmap
            levelBitmap = BitmapFactory.decodeStream(ins);
            backgroundPainting.setImageBitmap(levelBitmap);
      } catch (final IOException e) {
            e.printStackTrace();
            Toast.makeText(levelView.this, "couldn't set image to background", Toast.LENGTH_LONG).show();
      }

请帮助谢谢,

企鹅

【问题讨论】:

  • 你的 toast 会在跑步时出现吗?
  • 如果没有,你打电话给setContentView(rel)吗?
  • 是的,我的吐司很好。我有一个自定义 GamePanel,我将其设置为内容视图,但它是一个不同的类。
  • 请发布异常,然后您会在 LogCat 中找到它。

标签: android background bitmap imageview


【解决方案1】:

您必须首先在 xml 文件中创建一个线性布局。 然后在您的代码中访问该布局。

LinearLayout linearMain = (LinearLayout) findViewById(R.id.linearmainLayout);

然后在 backgroundPainting 中设置位图图像后,通过在最后添加这两行来尝试下面的事情

rel.addView(backgroundPainting, lp);

linearMain.addView(rel);

或者你可以试试这个方法

setContentView(rel); 

在backgroundPainting中设置位图图像后在最后写一行

rel.addView(backgroundPainting, lp); 

【讨论】:

  • 所以你说我不能只在代码中构造一个新的 LinearLayout,然后在没有 xml 文件的情况下添加一个 Image 视图?
【解决方案2】:

您必须将此视图 rel 添加到其父视图,该视图正在创建但未添加

【讨论】:

    【解决方案3】:

    在创建LinearLayout 后使用setContentView(rel);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多