为什么我的imageview不采用位图并显示它?

时间:2017-03-17 18:43:35

标签: java android

public class UserlistActivity extends AppCompatActivity {

    static ListView userlist;
    static String[] users;
    ImageView user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userlist);
        setIDs();
        Bitmap userphoto = null;
        try {
            userphoto = getBitmapFromAsset("user dashboard.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Gate(this, "USERLIST").execute();
        String mDrawableName = "user dashboard";
        int resID = getResources().getIdentifier(mDrawableName , "assets", getPackageName());
        user.setImageResource(resID);
        user.setImageBitmap(userphoto);
    }

    private Bitmap getBitmapFromAsset(String strName) throws IOException
    {
        AssetManager assetManager = getAssets();
        InputStream istr = assetManager.open(strName);
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
        return bitmap;
    }

    private void setIDs() {
        userlist = (ListView) findViewById(R.id.userlist);
        View inflatedView = getLayoutInflater().inflate(R.layout.userlist_list_item, null);
        user = (ImageView) inflatedView.findViewById(R.id.user);
    }

    static void fillData(Context context) {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, R.layout.userlist_list_item, R.id.listtext, users);
        userlist.setAdapter(arrayAdapter);
    }

这里我正在尝试getbitmap(在其他活动中工作正常)并将其附加到图像视图,这是我传递给适配器的列表项自定义布局的一部分,但我不知道问题出在哪里,图像没有出现

编辑::

我通过添加照片的另一个副本来修复它,以便我可以添加源代码并跳过努力

1 个答案:

答案 0 :(得分:1)

我认为您忘记将inflatedView添加到parent视图

使用此代码:

 LinearLayout parent = (LinearLayout)findViewById(R.id.parent_layout);
View inflatedView = getLayoutInflater().inflate(R.layout.userlist_list_item, null);
user = (ImageView) inflatedView.findViewById(R.id.user);
parent.addView(inflatedView);

使用以下方法:

private Bitmap getBitmapFromAsset(String strName)
{
    AssetManager assetManager = getAssets();
    InputStream istr = null;
    try {
        istr = assetManager.open(strName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    return bitmap;
}