0

我正在为 Android 设计一个键盘。通过在我的 MainActivity 中实现 View.OnTouchListener,我刚刚学会了在 onCreate 方法中定义按钮的简洁方法:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    defineButtons();


    keyC.setOnTouchListener(this);
//etc..

}

接着:

    private void defineButtons()
{

    keyC = (Button) findViewById(R.id.c);
//etc..
}

然后我会定义当按钮被这个方法触摸时会发生什么:

public boolean onTouch(View view, MotionEvent motion)
{
    int note = 0;

    switch(view.getId())
    {

    case R.id.c:    /** Note C*/
    {
        note = 60 + transposeOctave;
        motionTracker(view, motion, note);
    }
    break;
//etc...
}

最后一种方法必须分别为每个按钮重复,这看起来有点难看。我可以使用 Id 返回一个数值来修改我的注释值吗?

干杯

4

3 回答 3

1

Are your keys defined in XML? If so, I would simply add a tag to each one with the proper numeric value, like so:

android:tag="1"

Then, in your code, you can simply do this:

int note = 0;
int tagValue = 0;

//Tags in XML are always strings
String tag = (String)view.getTag();

//Parse it to an integer
tagValue = Integer.parseInt(tag);

note = tagValue + transposeOctave;
motionTracker(view, motion, note);
于 2012-09-24T15:01:19.950 回答
0

You can't force an ID to a specific value. There is no way to do it in Android, the Android Asset Packaging Tool (AAPT) will always automatically generate them for you.

But you can still hide the "ugly" conversion from constant to integer in a function. example: keyboardIdToFrequency()

于 2012-09-24T15:00:54.507 回答
0

您可以使用将特定值添加为标签

btn.setTag("something");

并在 onTouch 中使用

Button btn = (Button)view;

String val = btn.Gettag();
note = Integer.Valueof(val)+ transposeOctave;
于 2012-09-24T15:11:23.097 回答