简体   繁体   中英

Creating dynamic buttons in android

I am working on Watson Conversation chatbot. I have been trying to implement the 'options' response type in my chatbot application. My problem is "Creating 'n' number of dynamic buttons in Android where n is the number of label names of options present in the backend(IBM Watson Conversation)"

I have been able to retrieve the label names in form of text. Now I have to put these label names in "clickable buttons". Such that when a user clicks on a button, a value is passed to the backend (Watson Conversation API).

This is how I am retrieving option(response type) from backend. Watson Conversation sends reply in form of JSON.

Label name retrieving code:

 str = response.getOutput().getGeneric().get(i).getResponseType();
JSONArray arrayOptions = new JSONArray(response.getOutput().getGeneric().get(i).getOptions());
            int j=0; //j is used to count the number of options
            while (j<arrayOptions.length()){
              final Message outMessage2 = new Message();
              outMessage2.setMessage(response.getOutput().getGeneric().get(i).getOptions().get(j).getLabel());
              outMessage2.setId("2");
              System.out.println(outMessage2);
              messageArrayList.add(outMessage2);
              j++;
            }

Try this to solve your problem

First create a LinearLayout Layout inside xml

                 <LinearLayout
                    android:id="@+id/layout_dynamic"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:orientation="vertical">

                </LinearLayout>

After that, use below code

LinearLayout layout_dynamic =(LinearLayout) findViewById(R.id.layout_dynamic);

for (int i = 0; i < YOURARRAY.length(); i++) {
String label = <Button Name as You Like>;
 LinearLayout childLayout = new LinearLayout(getActivity());
 LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
 LinearLayout.LayoutParams.MATCH_PARENT LinearLayout.LayoutParams.WRAP_CONTENT);
 childLayout.setLayoutParams(linearParams);
 Button btnName = new Button(getActivity());
 btnName.setLayoutParams(newTableLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT, 1f));

 childLayout.addView(btnName, 0);
 layout_dynamic.addView(childLayout);}

Hope this will help you.

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