Java 如何提前获得我的按钮的尺寸?

Java 如何提前获得我的按钮的尺寸?,java,android,Java,Android,大家好,我基本上是在做一个钢琴应用程序。经过深思熟虑,我想我已经了解了大多数钢琴应用程序是如何完成的,我被困在这里,这似乎对于获得所有其他功能(如幻灯片、多点触摸、添加按键等)非常关键 有没有可能事先知道我的可拉拔按钮的尺寸? 假设我基本上有两个可拉拔键按钮,钢琴键C和D: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" a

大家好,我基本上是在做一个钢琴应用程序。经过深思熟虑,我想我已经了解了大多数钢琴应用程序是如何完成的,我被困在这里,这似乎对于获得所有其他功能(如幻灯片、多点触摸、添加按键等)非常关键

有没有可能事先知道我的可拉拔按钮的尺寸? 假设我基本上有两个可拉拔键按钮,钢琴键C和D:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:gravity="bottom" >

<Button
    android:id="@+id/ckey"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/keybutton" />

<Button
    android:id="@+id/dkey"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/keybutton" />

对于钢琴应用程序(白键),它们都使用相同的选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item 
    android:drawable="@drawable/key"
    android:state_pressed="true"/>

<item 
    android:drawable="@drawable/key_pressed"/>
</selector>

但我想事先知道创建的按钮的尺寸或位置,这样我就可以在按钮顶部绘制一个区域,并使用该区域进行操作。我需要那个区域,这样我就可以使用onTouch了

@Override
public boolean onTouch(View v, MotionEvent event) {

int numberOfKeys = 2;
Region[] keyBoard = new Region[2]; //for 2 White Piano Keys
Integer pointerIndex = event.getActionIndex();
Float x = event.getX(pointerIndex);
Float y = event.getY(pointerIndex);

for(int j=0;j<1;j++){
    if(this.keyBoard[j].contains(x.intValue(),y.intValue())){
           //play corresponding sound

        }
@覆盖
公共布尔onTouch(视图v,运动事件){
int numberOfKeys=2;
区域[]键盘=新区域[2];//用于2个白色钢琴键
整数pointerIndex=event.getActionIndex();
Float x=event.getX(pointerIndex);
Float y=event.getY(pointerIndex);

对于(int j=0;j您可以在布局中设置按钮的宽度/高度,而不仅仅是使用
wrap\u content

例如:
android:layout\u width=“100dp”


**编辑:不要这样做,不推荐使用**您也可以使用(如果您想准确地设置显示内容的位置,请不要选择当前的
LinearLayout

您不需要事先知道。搜索
GlobalLayoutListener
。这些问题的一些答案也会将您带到生命周期中除onCreate()之外的其他地方,在onCreate()中您可能可以这样做。在onCreate()中),布局尚未生成,维度将始终为零。此文档可能会有所帮助:使用
setOnTouchListener(OnTouchListener)有什么问题
按钮上
本身?为什么在它上面画一个区域?作为
GlobalLayoutListener
的替代方案:一个
可运行的
,例如
按钮
并从那里启动你的区域。请看:@zapl Oooh,我喜欢。谢谢!
绝对布局?
从…永远以来,它没有被弃用过吗?我喜欢这个答案,我不喜欢hink我已经完成了应用程序。我在这里完成了;D。