Создать собственный диалог со списком переключателей

Первоначально опубликовано в форуме PrimeFaces @ http://forum.primefaces.org/viewtopic.php?f=3&t=29546

Недавно я был одержим оценивая производительность моего приложения, настраивая запросы JPA, заменяя динамические SQL-запросы именованными запросами, и только сегодня утром я узнал, что метод getter больше похож на HOT SPOT в Java Visual VM, чем остальная часть моего кода (или большинства мой код).

Метод Getter:

PageNavigationController.getGmapsAutoComplete()

Ссылка на ui: include in in index.xhtml

Ниже вы увидите, что PageNavigationController.getGmapsAutoComplete () является HOT SPOT (проблема с производительностью) в Java Visual VM. Если вы посмотрите дальше, на экране захвата, вы увидите, что getLazyModel (), PrimeFaces ленивый метод datatable getter, также является горячей точкой, только когда enduser делает много «ленивых данных» типа вещей / операций / задач в приложении. :]

Java Visual VM: showing HOT SPOT [/g1]

См. (исходный) код ниже.

public Boolean getGmapsAutoComplete() {
    switch (page) {
        case "/orders/pf_Add.xhtml":
        case "/orders/pf_Edit.xhtml":
        case "/orders/pf_EditDriverVehicles.xhtml":
            gmapsAutoComplete = true;
            break;
        default:
            gmapsAutoComplete = false;
            break;
    }
    return gmapsAutoComplete;
}

Называется в index.xhtml:


    

Решение: поскольку это метод «getter», переместите код и присвойте значение gmapsAutoComplete до вызова метода; см. код ниже.

/*
 * 2013-04-06 moved switch {...} to updateGmapsAutoComplete()
 *            because performance = 115ms (hot spot) while
 *            navigating through web app
 */
public Boolean getGmapsAutoComplete() {
    return gmapsAutoComplete;
}

/*
 * ALWAYS call this method after "page = ..."
 */
private void updateGmapsAutoComplete() {
    switch (page) {
        case "/orders/pf_Add.xhtml":
        case "/orders/pf_Edit.xhtml":
        case "/orders/pf_EditDriverVehicles.xhtml":
            gmapsAutoComplete = true;
            break;
        default:
            gmapsAutoComplete = false;
            break;
    }
}

Результаты теста: PageNavigationController.getGmapsAutoComplete () больше не является HOT SPOT в Java Visual VM (больше не отображается)

тема, так как многие из опытных пользователей посоветовали младшим разработчикам JSF НЕ добавлять код в методы «getter». :)

29
задан End.Game 11 September 2015 в 10:05
поделиться

6 ответов

Позвоните showRadioButtonDialog() с кнопки.

Это всего лишь пример:

private void showRadioButtonDialog() {

        // custom dialog
        final Dialog dialog = new Dialog(mActivity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.radiobutton_dialog);
        List<String> stringList=new ArrayList<>();  // here is list 
        for(int i=0;i<5;i++) {
            stringList.add("RadioButton " + (i + 1));
        }
        RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.radio_group);

            for(int i=0;i<stringList.size();i++){
                RadioButton rb=new RadioButton(mActivity); // dynamically creating RadioButton and adding to RadioGroup.
                rb.setText(stringList.get(i));
                rg.addView(rb);
            }

        dialog.show();

    }

Ваше представление макета: radiobutton_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RadioGroup

        android:id="@+id/radio_group"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"


        android:layout_gravity="center_vertical"
        android:orientation="vertical">


    </RadioGroup>
</LinearLayout>

enter image description here

Примечание: вы можете настроить диалоговое окно (например, установить заголовок, сообщение и т. Д.)

Редактировать: Для получения значения выбранного реализовать setOnCheckedChangeListener слушатель для вашего RadioGroup как:

 rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                 int childCount = group.getChildCount();
                 for (int x = 0; x < childCount; x++) {
                    RadioButton btn = (RadioButton) group.getChildAt(x);
                    if (btn.getId() == checkedId) {
                         Log.e("selected RadioButton->",btn.getText().toString());

                    }
                 }
            }
        });
37
ответ дан Vasily Kabunov 11 September 2015 в 10:05
поделиться

Это сработало для меня:

final CharSequence[] items = {"Option-1", "Option-2", "Option-3", "Option-4"};

AlertDialog.Builder builder = new AlertDialog.Builder(ShowDialog.this);
builder.setTitle("Alert Dialog with ListView and Radio button");
builder.setIcon(R.drawable.icon);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
 Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});

builder.setPositiveButton("Yes",
 new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int id) {
   Toast.makeText(ShowDialog.this, "Success", Toast.LENGTH_SHORT).show();
  }
 });
builder.setNegativeButton("No",
 new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int id) {
   Toast.makeText(ShowDialog.this, "Fail", Toast.LENGTH_SHORT).show();
  }
 });
AlertDialog alert = builder.create();
alert.show();
4
ответ дан Akay 11 September 2015 в 10:05
поделиться

Чистый способ выглядит следующим образом:

http://developer.android.com/guide/topics/ui/dialogs.html

Выдержка из ( Добавление постоянного списка с несколькими или одним выбором)

mSelectedItems = new ArrayList();  // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
       .setMultiChoiceItems(R.array.toppings, null,
                  new DialogInterface.OnMultiChoiceClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which,
                   boolean isChecked) {
               if (isChecked) {
                   // If the user checked the item, add it to the selected items
                   mSelectedItems.add(which);
               } else if (mSelectedItems.contains(which)) {
                   // Else, if the item is already in the array, remove it 
                   mSelectedItems.remove(Integer.valueOf(which));
               }
           }
       })
// Set the action buttons
       .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int id) {
               // User clicked OK, so save the mSelectedItems results somewhere
               // or return them to the component that opened the dialog
               ...
           }
       })
       .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int id) {
               ...
           }
       });

return builder.create();

Читать о http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setSingleChoiceItems ( int, int, android.content.DialogInterface.OnClickListener)

Настраиваемое представление не требуется.

7
ответ дан JoxTraex 11 September 2015 в 10:05
поделиться

лучший и простой способ ......

void dialog(){

        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        //alt_bld.setIcon(R.drawable.icon);
        alt_bld.setTitle("Select a Group Name");
        alt_bld.setSingleChoiceItems(grpname, -1, new DialogInterface
                .OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(),
                        "Group Name = "+grpname[item], Toast.LENGTH_SHORT).show();
                dialog.dismiss();// dismiss the alertbox after chose option

            }
        });
        AlertDialog alert = alt_bld.create();
        alert.show();


///// grpname is a array where data is stored... 


    }
59
ответ дан kRiZ 11 September 2015 в 10:05
поделиться

, когда вы хотите показать данные из базы данных SQLIte,

private void showRadioButtonDialog() {

    // custom dialog
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.radiobutton_dialog);
    List<String> stringList=new ArrayList<>();  // here is list 

    if (cursor.moveToFirst()) {
        do {
            String a=( cursor.getString(0).toString());
            String b=(cursor.getString(1).toString());
            String c=(cursor.getString(2).toString());
            String d=(cursor.getString(3).toString());
            stringList.add(d);
        } while (cursor.moveToNext());        
    }   

    RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.radio_group);

    for(int i=0;i<stringList.size();i++) {
        RadioButton rb=new RadioButton(this); // dynamically creating RadioButton and adding to RadioGroup.
        rb.setText(stringList.get(i));
        rg.addView(rb);
    }

    dialog.show();

    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

         @Override
         public void onCheckedChanged(RadioGroup group, int checkedId) {
             int childCount = group.getChildCount();
             for (int x = 0; x < childCount; x++) {
                 RadioButton btn = (RadioButton) group.getChildAt(x);
                 if (btn.getId() == checkedId) {
                     Toast.makeText(getApplicationContext(), btn.getText().toString(), Toast.LENGTH_SHORT).show();
                 }
             }
         }
     });
}
0
ответ дан V-rund Puro-hit 11 September 2015 в 10:05
поделиться

Проверьте это. Это пользовательская строка dialog_row.xml, которую вы должны использовать в CustomAdapter:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical" android:layout_width="match_parent"
      android:layout_height="match_parent">

    <RadioButton
       android:id="@+id/list"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />
    </LinearLayout>

Затем в методе onclick:

@Override
public void onClick(View arg0) {

    // custom dialog
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.custom_layout); //Your custom layout
    dialog.setTitle("Title...");


    Listview listview= (ListView) dialog.findViewById(R.id.listview);

    CustomAdapter adapter=new CustomAdapter(context,your_list);
    listview.setadapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Do something

        }
    });

    dialog.show();
}

Ссылка на учебное пособие

1
ответ дан Edric 11 September 2015 в 10:05
поделиться
Другие вопросы по тегам:

Похожие вопросы: