java - 如何从 Json 字符串动态创建按钮

标签 java android json

我将 URL 中的 JSON 数据解析为列表,现在我想为列表中的每个项目创建按钮,但我不知道如何执行此操作。我不确定该列表是否是最好的主意,但这是我在网上找到的解决方案。

public class SecondActivity extends AppCompatActivity {

    private String TAG = SecondActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    private static String url = "https://ggysqqcz.p51.rt3.io/available-remotes/TV";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();

    }


    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SecondActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray remotes = jsonObj.getJSONArray("remotes");

                    // looping through All Contacts
                    for (int i = 0; i < remotes.length(); i++) {
                        JSONObject c = remotes.getJSONObject(i);

                        String id = c.getString("id");


                        HashMap<String, String> contact = new HashMap<>();


                        contact.put("id", id);

                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;

        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();


            ListAdapter adapter = new SimpleAdapter(

                    SecondActivity.this, contactList,
                  R.layout.list_item, new String[]{"id"}, new int[]{button1});

            lv.setAdapter(adapter);


        }
    }

public void onClickButton1(View view) {
        startActivity(new Intent(getApplicationContext(), ThirdActivity.class));
    }
}

这显示了所有按钮,但显然它们在单击时都会执行相同的操作,因为我只有button1。如何让所有按钮执行不同的操作?

最佳答案

我想建议为您的 ListView 创建一个自定义适配器,它将为您的按钮提供一个 onClick 函数,并基于该项目在 中的位置>ListView,您可以在onClick函数中实现不同的操作。因此我想推荐一个如下所示的适配器。

public class ListAdapter extends ArrayAdapter<Item> {

    private int resourceLayout;
    private Context mContext;
    private ArrayList<Contact> contacts;

    public ListAdapter(Context context, int resource, ArrayList<Contact> contacts) {
        super(context, resource, items);
        this.resourceLayout = resource;
        this.mContext = context;
        this.contacts = contacts;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(mContext);
            v = vi.inflate(resourceLayout, null);
        }

        Item p = getItem(position);

        if (p != null) {
            Button btn = (TextView) v.findViewById(R.id.button1);

            if (btn != null) {
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(position == 1) implementSomethingFor1();
                        else if (position == 2) implementSomethingFor2();
                        // ... Define the other implementations
                    }
                });
            }
        }

        return v;
    }
}

然后使用适配器,如下所示。

ListView lv = (ListView) findViewById(R.id.list);
ListAdapter customAdapter = new ListAdapter(this, R.layout.list_item, contactList);
lv.setAdapter(customAdapter);

请注意,这不是一个精确的实现。您应该修改您的自定义适配器,以便它满足您的目的。

关于java - 如何从 Json 字符串动态创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727116/

相关文章:

c# - RestSharp POST 对象作为 JSON

java - 如何通过 REST (JAX-RS) 在 web.xml 中声明多个包?

java - 如何向 Web 服务发送 HTTP POST?

android - 首选项屏幕崩溃

java - 如何使用 httpPost 将数据发送到网站,应用程序崩溃

javascript - 资源解释为文档,但使用 MIME 类型 application/json 进行传输

json - 使用经典ASP访问请求的正文?

java - 这个升级演示如何运作?

java - NullPointerException 进入 onPostExecute 方法

当我杀死我的应用程序时,Java android 服务没有被破坏