我认为最好先说,我最近开始使用Android编程。尽管我现在变得越来越好,但我似乎无法找到优化我的代码的好方法。
我写过这段代码。这是一个音板。当您长按一个按钮时,您可以将其保存为铃声,闹钟,通知或与朋友分享。对于我制作字符串的每种方法。
此字符串由相应按钮设置为“btn1”直到“btn20”。在此之后我打开方法(在下面的例子中showSelectedSaveDialog()
。在那个方法中,我做了一个if或if else语句来打开正确的声音。
这种编码方式会产生很长的代码。因为对于每个按钮,我必须发出if else
语句。有没有更好的方法来编码种类代码?有没有一个很好的教程,或类似的东西?或者可以发布示例的人?
Setting the string:
ringToneManager = "btn1";
showSelectSaveDialog();
Setting the correct sound:
if (str.equals("btn1")) {
fIn = getSherlockActivity().getBaseContext().getResources()
.openRawResource(R.raw.sound01);
Starting the method to share the sound file
shareButton("btn14");
Getting the corresponding sound file
private void shareButton(String str) {
// SAVE THE FILE
byte[] buffer = null;
if (str.equals("btn1")) {
fIn = getSherlockActivity().getBaseContext().getResources()
.openRawResource(R.raw.sound01);
[...] etc
提前致谢! :)
答案 0 :(得分:1)
您可以使用所有视图和小部件上提供的“tag”属性来简化代码。 tag属性是一个通用容器。
使用与按钮关联的声音文件的id加载每个按钮的标记属性,这可以在onCreate上的活动中完成:
findViewById(R.id.btn1).setTag(R.raw.sound01);
findViewById(R.id.btn2).setTag(R.raw.sound02);
//etc.
findViewById(R.id.btn20).setTag(R.raw.sound20);
每个按钮现在可以共享相同的onClick处理程序,并且所有按钮都运行相同的代码,如果需要,则不需要:
public void onClick(View arg0) {
fIn = getSherlockActivity().getBaseContext().getResources().openRawResource((Integer)arg0.getTag());
}
同样将shareButton方法更改为取整数而不是字符串:
shareButton((Integer)arg0.getTag());
private void shareButton(int soundID) {
// SAVE THE FILE
byte[] buffer = null;
fIn = getSherlockActivity().getBaseContext().getResources().openRawResource(soundID);
[...] etc