我正在创建一个Youtube Player应用。我不明白如何在动态多个按钮中分配JSON对象值。我正在通过JSON提取数据,并将数据转换为JSON数组。我希望通过JSON对象分配Button背景图片,URL视频以及按钮名称,请帮助我???
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parent=(LinearLayout)findViewById(R.id.ll_parent);
BackgroundTask process = new BackgroundTask();
process.execute();
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
String data = "";
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new
URL("https://manisheikh.com/hamza/Json_get_Button_Data.php");
HttpsURLConnection httpsURLConnection = (HttpsURLConnection)
url.openConnection();
InputStream inputStream = httpsURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));
String line = "";
while ((line != null)) {
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA=new JSONArray(data);
for(int i=0;i<JA.length();i++)
{
JSONObject JO=(JSONObject) JA.get(i);
b1=new Button(MainActivity.this);
b1.setId(i+1);
b1.setText((CharSequence) JO.get("btn_name"));
b1.setTag(i);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
parent.addView(b1);
return;
}
}
答案 0 :(得分:0)
尝试
for(int i = 0; i < JA.length(); i++)
{
Button btn = new Button(this);
btn.setId(2000+i);
btn.setText(JA.get(i) + i));
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(view v) {
// TODO Whatever you want onclick to do
}
});
//Log stuff
linearButton.addView(btn, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
注意:-不要忘记最后添加视图