如何在点击按钮android上调用以下void?

时间:2011-10-18 19:31:30

标签: java android call void

我有以下代码,我想调用此代码onclick按钮 我怎么能这样做?

public static void main(String[] args) throws Exception {
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search = "stackoverflow";
String charset = "UTF-8";

URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);

// Show title and URL of 1st result.
System.out.println(results.getResponseData().getResults().get(0).getTitle());
System.out.println(results.getResponseData().getResults().get(0).getUrl());

}

2 个答案:

答案 0 :(得分:1)

首先你应该改变一些事情。您不应该将方法命名为main。在android中你不使用main方法。同样在Android中,您不使用System.out.println,而是使用Android Log类。

我会将方法更改为:

public static void doSomething() throws Exception {
    String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
    String search = "stackoverflow";
    String charset = "UTF-8";

    URL url = new URL(google + URLEncoder.encode(search, charset));
    Reader reader = new InputStreamReader(url.openStream(), charset);
    GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);

    // Show title and URL of 1st result.
    String tag = "myTag";
    Log.d(tag, results.getResponseData().getResults().get(0).getTitle());
    Log.d(tag, results.getResponseData().getResults().get(0).getUrl());
}

然后,当您定义OnClickListener时,只需在onClick()方法中调用上述方法:

public void onClick(View v){
    doSomething();
}

答案 1 :(得分:0)

让我们说点击的按钮叫做myButton。然后你会这样做:

myButton.addOnClickListener(new View.OnClickListener(){
   public void onCick(View view){
     String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
     String search = "stackoverflow";
     String charset = "UTF-8";

     URL url = new URL(google + URLEncoder.encode(search, charset));
     Reader reader = new InputStreamReader(url.openStream(), charset);
     GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
   });

我拿出了System.out.println因为你无法在android中真正做到这一点。您可以尝试打印到日志,制作Toasts或进行其他类型的输出。