2012-05-03 5 views
0

제목에 내 코드를 간소화하기 위해 도움을 얻으려고합니다. 여러 개의 버튼이 있는데, 지금은 3 개 밖에 테스트하지 않지만 약 30 개의 버튼을 선택할 계획입니다. 현재 코드의 섹션이 매우 길어서 배열을 사용하여 크게 단축 될 수 있다고 생각합니다. 하지만 올바르게 구현하는 방법을 모르겠습니다. 누구나 전에 이것을했거나 아이디어가 있다면 공유하십시오! 모두에게 감사 드려요! 하나Android - 내 코드 단순화 : 한 가지 방법으로 연결된 여러 버튼

public class myDL extends Activity { 

public static final int DIALOG_DOWNLOAD_PROGRESS = 0; 
private Button startBtn; 
private ProgressDialog mProgressDialog; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.filechoice); 
mProgressDialog = new ProgressDialog(myDL.this); 
mProgressDialog.setMessage("The file is now downloading, it will be saved on the SD card for future use. Please use WiFi to avoid operator charges."); 
mProgressDialog.setIndeterminate(false); 
mProgressDialog.setMax(100); 
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 

Button section = (Button) findViewById(R.id.section); 
section.setOnClickListener(new View.OnClickListener() { 

    public void onClick(View view) { 
     // TODO Auto-generated method stub 
     Intent section = new Intent(view.getContext(), 
       section.class); 
     startActivity(section); 

    } 
}); 

Button back = (Button) findViewById(R.id.back); 
back.setOnClickListener(new View.OnClickListener() { 

    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     setResult(RESULT_OK); 
     finish(); 
    } 
}); 

secOne = (Button) findViewById(R.id.secOne); 
secOne.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
     startSecOne(); 
    } 

}); 
} 

private void startSecOne() { 
StartSecOne secOne = new StartSecOne(); 
secOne 
     .execute("www.website.com/document.pdf"); 

} 

class StartSecOne extends AsyncTask<String, Integer, String> { 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    mProgressDialog.show(); 
} 

@Override 
protected void onProgressUpdate(Integer... progress) { 
    super.onProgressUpdate(progress); 
    mProgressDialog.setProgress(progress[0]); 
} 

@Override 
protected String doInBackground(String... aurl) { 

    String isFileThere = Environment.getExternalStorageDirectory() 
      + "/Android/Data/" 
      + getApplicationContext().getPackageName() 
      + "/files/test1.pdf"; 
    File f = new File(isFileThere); 

    if (f.exists()) { 
     showPdf(); 
    } else { 

     try { 

      URL url = new URL(aurl[0]); 
      URLConnection connection = url.openConnection(); 

      connection.connect(); 
      int fileLength = connection.getContentLength(); 
      int tickSize = 2 * fileLength/100; 
      int nextProgress = tickSize; 

      Log.d( 

      "ANDRO_ASYNC", "Lenght of file: " + fileLength); 

      InputStream input = new BufferedInputStream( 
        url.openStream()); 

      String path = Environment.getExternalStorageDirectory() 
        + "/Android/Data/" 
        + getApplicationContext().getPackageName() 
        + "/files"; 
      File file = new File(path); 
      file.mkdirs(); 
      File outputFile = new File(file, "test1.pdf"); 

      OutputStream output = new FileOutputStream(outputFile); 

      byte data[] = new byte[1024 * 1024]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       if (total >= nextProgress) { 
        nextProgress = (int) ((total/tickSize + 1) * tickSize); 
        this.publishProgress((int) (total * 100/fileLength)); 
       } 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
      mProgressDialog.dismiss(); 
      showPdf(); 

     } catch (Exception e) { 
     } 
    } 
    return null; 
} 
} 
secTwo = (Button) findViewById(R.id.secTwo); 
secTwo.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
     startSecTwo(); 
    } 

}); 
} 

private void startSecTwo() { 
StartSecTwo secTwo = new StartSecTwo(); 
secTwo 
     .execute("www.website.com/document2.pdf"); 

} 

class StartSecTwo extends AsyncTask<String, Integer, String> { 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    mProgressDialog.show(); 
} 

@Override 
protected void onProgressUpdate(Integer... progress) { 
    super.onProgressUpdate(progress); 
    mProgressDialog.setProgress(progress[0]); 
} 

@Override 
protected String doInBackground(String... aurl) { 

    String isFileThere = Environment.getExternalStorageDirectory() 
      + "/Android/Data/" 
      + getApplicationContext().getPackageName() 
      + "/files/test2.pdf"; 
    File f = new File(isFileThere); 

    if (f.exists()) { 
     showPdf(); 
    } else { 

     try { 

      URL url = new URL(aurl[0]); 
      URLConnection connection = url.openConnection(); 

      connection.connect(); 
      int fileLength = connection.getContentLength(); 
      int tickSize = 2 * fileLength/100; 
      int nextProgress = tickSize; 

      Log.d( 

      "ANDRO_ASYNC", "Lenght of file: " + fileLength); 

      InputStream input = new BufferedInputStream( 
        url.openStream()); 

      String path = Environment.getExternalStorageDirectory() 
        + "/Android/Data/" 
        + getApplicationContext().getPackageName() 
        + "/files"; 
      File file = new File(path); 
      file.mkdirs(); 
      File outputFile = new File(file, "test2.pdf"); 

      OutputStream output = new FileOutputStream(outputFile); 

      byte data[] = new byte[1024 * 1024]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       if (total >= nextProgress) { 
        nextProgress = (int) ((total/tickSize + 1) * tickSize); 
        this.publishProgress((int) (total * 100/fileLength)); 
       } 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
      mProgressDialog.dismiss(); 
      showPdf(); 

     } catch (Exception e) { 
     } 
    } 
    return null; 
} 
} 

secThree = (Button) findViewById(R.id.secThree); 
secThree.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
     startSecThree(); 
    } 

}); 
} 

private void startSecThree() { 
StartSecThree secThree = new StartSecThree(); 
secThree 
     .execute("www.website.com/document3.pdf"); 

} 

class StartSecThree extends AsyncTask<String, Integer, String> { 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    mProgressDialog.show(); 
} 

@Override 
protected void onProgressUpdate(Integer... progress) { 
    super.onProgressUpdate(progress); 
    mProgressDialog.setProgress(progress[0]); 
} 

@Override 
protected String doInBackground(String... aurl) { 

    String isFileThere = Environment.getExternalStorageDirectory() 
      + "/Android/Data/" 
      + getApplicationContext().getPackageName() 
      + "/files/test3.pdf"; 
    File f = new File(isFileThere); 

    if (f.exists()) { 
     showPdf(); 
    } else { 

     try { 

      URL url = new URL(aurl[0]); 
      URLConnection connection = url.openConnection(); 

      connection.connect(); 
      int fileLength = connection.getContentLength(); 
      int tickSize = 2 * fileLength/100; 
      int nextProgress = tickSize; 

      Log.d( 

      "ANDRO_ASYNC", "Lenght of file: " + fileLength); 

      InputStream input = new BufferedInputStream( 
        url.openStream()); 

      String path = Environment.getExternalStorageDirectory() 
        + "/Android/Data/" 
        + getApplicationContext().getPackageName() 
        + "/files"; 
      File file = new File(path); 
      file.mkdirs(); 
      File outputFile = new File(file, "test3.pdf"); 

      OutputStream output = new FileOutputStream(outputFile); 

      byte data[] = new byte[1024 * 1024]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       if (total >= nextProgress) { 
        nextProgress = (int) ((total/tickSize + 1) * tickSize); 
        this.publishProgress((int) (total * 100/fileLength)); 
       } 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
      mProgressDialog.dismiss(); 
      showPdf(); 

     } catch (Exception e) { 
     } 
    } 
    return null; 
} 
} 



private void showPdf() { 
    // TODO Auto-generated method stub 
    mProgressDialog.dismiss(); 
    File file = new File(Environment.getExternalStorageDirectory() 
      + "/Android/Data/" 
      + getApplicationContext().getPackageName() 
      + "/files/test1.pdf"); 
    PackageManager packageManager = getPackageManager(); 
    Intent testIntent = new Intent(Intent.ACTION_VIEW); 
    testIntent.setType("application/pdf"); 
    List list = packageManager.queryIntentActivities(testIntent, 
      PackageManager.MATCH_DEFAULT_ONLY); 
    Intent intent = new Intent(); 
    intent.setAction(Intent.ACTION_VIEW); 
    Uri uri = Uri.fromFile(file); 
    intent.setDataAndType(uri, "application/pdf"); 
    startActivity(intent); 
} 


} 

답변

3
final OnClickLisener listener = new OnClickListener() { 
    public void onClick(View v){ 
     switch(v.getId()){ 
     case R.id.zero: 
      break; 
     case R.id.one: 
      break; 
     case R.id.two: 
      break; 
     } 
    } 
} 
final int[] btnIds = new int[]{R.id.one, R.id.two, R.id.zero}; 
for(int i = 0; i < btnIds.length; i++) { 
    final Button btn = (Button)findViewById(btnIds[i]); 
    btn.setOnClickListener(listener); 
} 
+1

좋은! 이를 향상 시키려면 layout xml의 모든 버튼에 android : onClick = "onClick"속성을 추가하여 findViewById 호출을 모두 피할 수 있습니다. – marmor