试试这个,
public void listButtons() {
LinearLayout layout = (LinearLayout)findViewById(R.id.button_list);
String http_url = "http://example.com/demo";
try {
URL url = new URL(http_url);
HttpURLConnection con = HttpURLConnection)url.openConnection();
if(con!=null){
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String data=br.readLine();
JSONArray jsonArray=null;
jsonArray = new JSONArray(data);
Button tv[] = new Button[jsonArray.length()];
for(int i=0;i<jsonArray.length();i++)
{
tv[i] = new Button(this);
tv[i].setText(jsonArray.getJSONObject(i).getString("name"));
tv[i].setGravity(Gravity.CENTER_HORIZONTAL);
tv[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//add your code here
}
});
layout.addView(tv[i]);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我创建了一个布局 xml 文件,在其中添加了一个带有 id button_list 的线性布局
main.xml 文件-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".ResearchActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="55dp"
android:orientation="vertical"
android:id="@+id/button_list"
>
</LinearLayout>
</LinearLayout>