Как получить значение выбранного элемента в пользовательском представлении списка внутри AlertDialog? - PullRequest
0 голосов
/ 30 июня 2018

Я создал Пользовательский список внутри AlertDialog и установил данные, проанализировав список . Мне нужно получить значение кликаемого отдельного объекта этой кликаемой строки . Но listView.setOnItemClickListener не работает. Я пытался решить эту проблему, но не смог найти способ. Пожалуйста, помогите мне решить это.

Спасибо ..

вот мой код

AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle("Select A Customer");
            //insert array to constructor
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View dialogLayout = inflater.inflate(R.layout.product_list_pop_up, null);
            final CustomerPopupAdapter testAdapter = new CustomerPopupAdapter(getContext(), customers_data);
            ListView listView = dialogLayout.findViewById(R.id.product_list_view);
            TextView cancel_btn = dialogLayout.findViewById(R.id.cancel_btn);
            TextView done_btn = dialogLayout.findViewById(R.id.done_btn);
            listView.setAdapter(testAdapter);

            builder.setView(dialogLayout);

            final AlertDialog alert = builder.create();
            alert.show();

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    Log.d("selected Item", "ListView ");
//                    customerName = testAdapter.getItem(position);
//                    customer_name.setText((CharSequence) testAdapter.getItem(position));
                    alert.dismiss();
                }
            });
         alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

            cancel_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alert.dismiss();
                }
            });

            done_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alert.dismiss();
                }
            });

вот мой адаптер

public class CustomerPopupAdapter extends ArrayAdapter<Customer> {

    private List<Customer> list;

    public CustomerPopupAdapter(Context context, List<Customer> test) {
        super(context, R.layout.discount_popup_row, test);
        this.list = test;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(getContext());

        final Customer customer = list.get(position);
        View customRow = inflater.inflate(R.layout.customer_popup_row, parent, false);

        TextView customer_name = customRow.findViewById(R.id.customer_name);
        TextView customer_id = customRow.findViewById(R.id.customer_id);

        customer_id.setText(customer.getId());
        customer_name.setText(customer.getName());

        return customRow;
    }
}

вот custom_row.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/match_result"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_margin_10dp"
        android:weightSum="3">

        <TextView
            android:id="@+id/customer_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="Username"
            android:inputType="text"
            android:layout_weight="1"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_size_18sp" />


        <TextView
            android:id="@+id/customer_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="id"
            android:inputType="text"
            android:layout_weight="2"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_size_18sp" />
    </LinearLayout>

    <View
        android:id="@+id/bottom_border"
        android:layout_width="match_parent"
        android:layout_height="0.8dp"
        android:layout_marginTop="@dimen/activity_margin_5dp"
        android:background="@color/colorGrey" />

</LinearLayout>

Ответы [ 5 ]

0 голосов
/ 11 августа 2018

Пожалуйста, удалите android:inputType="text" из вашего xml. это решит вашу проблему. Благодаря.

0 голосов
/ 09 августа 2018

На самом деле, это ответ на этот вопрос. Я добавил android: inputType="text" к коду. Это была проблема. Я удалил его, и тогда он работает отлично.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/match_result"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_margin_10dp"
        android:weightSum="3">

        <TextView
            android:id="@+id/customer_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="Username"
            android:layout_weight="1"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_size_18sp" />


        <TextView
            android:id="@+id/customer_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="id"
            android:layout_weight="2"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_size_18sp" />
    </LinearLayout>

    <View
        android:id="@+id/bottom_border"
        android:layout_width="match_parent"
        android:layout_height="0.8dp"
        android:layout_marginTop="@dimen/activity_margin_5dp"
        android:background="@color/colorGrey" />

</LinearLayout>

Ответ был дан "I_A_Mok", все кредиты должны идти к нему.

0 голосов
/ 30 июня 2018

Вы, я не уверен, почему ваш код не работает, если вы можете опубликовать проект, который будет очень полезен или, по крайней мере, весь процесс, поэтому вы можете легко отобразить список в окне предупреждения.

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0: // horse
            case 1: // cow
            case 2: // camel
            case 3: // sheep
            case 4: // goat
        }
    }
});

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

Проверьте полный справочник https://stackoverflow.com/a/43532478/9638167

0 голосов
/ 30 июня 2018
  1. Не используйте ListView, прочитайте это: Должны ли мы использовать RecyclerView для замены ListView? и других материалов в Google, RecyclerView - это путь

  2. Я думаю, что вам нужно:

    lv.setOnItemClickListener(new OnItemClickListener(){
    
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
    { 
        //element selected is yourList.get(position);
    }
    });
    
0 голосов
/ 30 июня 2018

Используйте ваш список customers_data, чтобы получить значение щелчка.

           listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Log.d("selected Item", customers_data.get(position));
                    alert.dismiss();
                }
            });
...