转换为按钮控件(Android):究竟是什么? [英] Casting to a button control (Android): what exactly is that?

查看:157
本文介绍了转换为按钮控件(Android):究竟是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于投射的可用(类似)问题并没有真正阐明这是什么或做什么(顺便说一下,刚开始Android编程)。在哪里以及如何注意到投射的效果?

The available (similar) questions on "casting" don't really clarify what this is or does (just started Android programming, by the way). Where and how does one notice the effect of "casting"?

之间的区别是:

Button b = (Button) findViewById(R.id.btn_second)

Button b = findViewById(R.id.btn_second)

亲切的问候,

Pieter

推荐答案

试试这个,

findViewById(R.id.btn_second)  will return a View. 

但是它是什么类型的视图,Button,List,TextView,EditView等。

But what kind of view it is, a Button, a List, a TextView, EditView, etc.

这里findViewById(R.id.btn_second)返回一个Button类型的View,所以我们将它转​​换为Button类型。

Here findViewById(R.id.btn_second) is returning a View of type Button, so we to cast it to Button type.

Button b = (Button) findViewById(R.id.btn_second);

好的我会举个例子。

public abstract class Animal{
    public abstract void sound();
}

public class Dog extends Animal{
    public void sound(){
        System.out.println("Wooffffff");
    }
}

public class Cat extends Animal{
    public void sound(){
        System.out.println("Meowwwwwwww");
    }
}

现在如果我创建1只狗和1只猫对象。 。

Now if i create 1 dog and 1 cat object..

Dog d = new Dog();
Cat c = new Cat();

public class CloneAnimal{

    public void doIt(Animal a){
        if(a instanceof Dog)
            Dog d1 = (Dog) a;
        else 
            Cat c1 = (Cat) a ;
    }
}

(狗)和(猫)是明确的演员,喜欢(按钮)。

(Dog) and (Cat) are explicit cast, like (Button).

这篇关于转换为按钮控件(Android):究竟是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆