简体   繁体   中英

Android Java dynamic button click

I am generating buttons from the data I get from my JSON Object/Array. Getting from API. Currently I have 20 loops so to say (20 data, 20 buttons).

The xml / layout for the button looks like this:

    <Button
        android:id="@+id/details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

Currently the code to get the data and print it in my layout looks something like this:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


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

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://192.168.178.32:8888/test/public/index";
       ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        contactList = new ArrayList<>();

        new GetContacts().execute();
    lv = (ListView) findViewById(R.id.list);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

    @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 {
                // Getting JSON Array node
                JSONArray jsonArray = new JSONArray(jsonStr);

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

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

                    // tmp hash map for single contact
                    HashMap<String, String> data = new HashMap<>();

                    // adding each child node to HashMap key => value
                    data.put("id", id);
                    data.put("name", name);
                    data.put("description", description);

                    // adding contact to contact list
                    contactList.add(data);
                }
            } 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();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "description"}, new int[]{R.id.name,
                R.id.description, R.id.release_at});

        lv.setAdapter(adapter);
    }

And my Adapter looks like this:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private List<String> friends;
    private Activity activity;

    public RecyclerAdapter(Activity activity, List<String> friends, ArrayList<HashMap<String, String>> contactList) {
        this.friends = friends;
        this.activity = activity;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        //inflate your layout and pass it to view holder
        LayoutInflater inflater = activity.getLayoutInflater();
        View view = inflater.inflate(android.R.layout.simple_list_item_1, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder viewHolder, int position) {

        viewHolder.item.setText(friends.get(position));
    }

    @Override
    public int getItemCount() {
        return (null != friends ? friends.size() : 0);
    }

    /**
     * View holder to display each RecylerView item
     */
    protected class ViewHolder extends RecyclerView.ViewHolder {
        private TextView item;

        public ViewHolder(View view) {
            super(view);
            item = (TextView) view.findViewById(android.R.id.text1);
        }
    }

}

My idea is to click on each button and show the related data in another activity with more detail.

But how can I run through a loop and get the correct button (id) and create an new Activity with its related data.

In your adapter's getView method, you can set a onClickLister to the button in that row which will have a reference to that row's data. Use an intent to start the detailed activity and add the clicked item's data as an extra.

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

    //Inflate your row

    button.setOnClickListener(new OnClickListener(){
        @Override
        //On click function
        public void onClick(View view) {
             HashMap<String, String> item = contactsList.get(position);
             //Create the intent to start another activity
             Intent intent = new Intent(view.getContext(), DetailActivity.class);
             intent.putExtra("data", item);
             view.getContext().startActivity(intent);
        }
    });
});

In the receiving activity, you can get the data from the intent :

HashMap<String, String> data = getIntent().getExtras().getParcelableExtra("data");

Extend ArrayAdapter and pass your list of contacts in the constructor parameter to it. Assign that list to a field inside ArrayAdapter and then in your getView() method, you can get your item by simple list.get(position) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM