android - imageView.setImageBitmap 在 Android 中不起作用

标签 android android-layout

由 Emil 解决,谢谢 我的主要内容有以下内容

package com.example.surfacetest;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        //this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,     WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        ImageView img = (ImageView) findViewById(R.drawable.hero_frame);
        img.setImageBitmap(BitmapFactory.decodeResource(this.getResources(),R.drawable.chen_gong));

    }

}
`

在我的xml文件中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world"
    tools:context=".MainActivity" />
<ImageView
    android:id="@+id/hero1"
    android:maxWidth="100dp"
    android:maxHeight="100dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="centerInside"
    android:layout_marginLeft="5.33dp"
    />
<ImageView
    android:id="@+id/hero2"
    android:maxWidth="100dp"
    android:maxHeight="100dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="centerInside"
    android:layout_marginLeft="5.33dp"
    android:layout_toRightOf="@id/hero1"
    />

有什么我遗漏的吗?过去两天我一直在研究这个问题,但在互联网上找不到任何解决方案,或者我遗漏了它。请帮忙。

最佳答案

问题出在这一行:

    ImageView img = (ImageView) findViewById(R.drawable.hero_frame);

您需要传递要查找的 ImageView 的 ID,此时您可能会收到 NullPointerException,因为找不到 img,请尝试一下像这样:

    ImageView img = (ImageView) findViewById(R.id.hero1);

关于android - imageView.setImageBitmap 在 Android 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773788/

相关文章:

android - @style 属性在 api 24 及更低版本上崩溃

android - 增加选项卡布局中选项卡的宽度

java - 配置失败 : @AfterClass teardown error in appium

android - 为什么不应该使用 dpToPixel 来设置布局尺寸?

android - 我正在寻找如何为我的应用程序获取类似的选择器,例如 Android 的货币转换器。像这样的东西 :

android - 在三星 Galaxy Note Edge 上扩展类 android.support.design.widget.AppBarLayout 时出错

android - WebView:以编程方式清除 Service Worker 缓存

android - ADK 1.0 设备无法与 Jelly Bean 一起使用,为什么?

android - android 中的 gridview 选择器。如何?

java - 另一个应用程序中的 Activity 和服务之间的通信