【问题标题】:Type mismatch: cannot convert from View to ImageView类型不匹配:无法从 View 转换为 ImageView
【发布时间】:2014-12-11 09:16:10
【问题描述】:

我尝试清理、打开和关闭 Eclipse,仔细检查 id,仔细检查 R.java,但我不明白为什么会出现在行中

harryImageView = findViewById(R.id.harry);

有哪些可能的解决方案?

我的代码是:

 package com.example.imageview;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class ImageView extends ActionBarActivity {

    private ImageView harryImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_view);

        harryImageView = findViewById(R.id.harry);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.image_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

【问题讨论】:

  • 发布你的布局文件
  • 将 image_view.xml 添加到问题中

标签: android eclipse image casting imageview


【解决方案1】:

你的问题是你的班级被称为ImageView,这就是你在演员阵容中遇到问题的原因。

尝试以下方法:

android.widget.ImageView harryImageView;
//...
harryImageView = (android.widget.ImageView) findViewById(R.id.harry);

希望对你有帮助

【讨论】:

    【解决方案2】:

    findViewById(R.id.harry) 返回一个视图对象,它不识别它返回的视图类型。您需要执行以下操作:

    harryImageView = (ImageView) findViewById(R.id.harry);

    这样你告诉程序把返回的 View 看作一个 ImageView 对象。

    【讨论】:

    • 我这样做了,但即使程序告诉它不能投射......它应该向我显示一个建议列表,一个建议应该是投射,但他们没有建议预计。
    • 这是 Java 的基本功能,不是 IDE 提供的 :-) 另外,如果您觉得有用,请将答案标记为正确 :-)
    【解决方案3】:

    如果 (ImageView) 不起作用,请尝试以下代码

    (findViewById(R.id.harry) as ImageView)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-16
      • 2016-03-13
      • 2014-02-12
      • 2014-04-16
      • 2017-12-31
      • 2015-11-18
      • 2014-04-07
      • 2011-12-27
      相关资源
      最近更新 更多