viewにある全てのボタンを操作する

画面上にあるボタンを全て取得して、全部onClickListenerに登録したい。

refrectionを使って、R.id.の中身のstatic fieldsを全て取得して、一つずつfindViewByIdした。

import java.lang.reflect.*;

なおthisがimplements OnClickListenerされている。

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        for(Field f : R.id.class.getFields()){
            try{
                View v = this.findViewById((Integer)f.get(null));
                if(v.getClass().getName().equals("android.widget.Button")){
                    Button btn = (Button)v;
                    btn.setOnClickListener(this);
                }
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }

んで、clickイベントを取って、Buttonからのクリックイベントだったらボタン表面の文字列をhttp postする。

    public void onClick(View v) {
        if(v.getClass().getName().equals("android.widget.Button")){            
            Button btn = (Button)v;
            trace(btn.getText());
            HttpClient client = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://example.com/api");
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("message", btn.getText().toString()));
            try{
                httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                HttpResponse res = client.execute(httppost);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                res.getEntity().writeTo(os);
                trace(os.toString());
                trace("status : " + res.getStatusLine().getStatusCode());
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }