Попытка передать элемент и подпункт с помощью кнопки - PullRequest
0 голосов
/ 03 февраля 2019

Я пытаюсь передать значения из EditText (элемент и подэлемент) с помощью кнопки в просмотр списка

Я могу просмотреть TextView, но есть ли способ передать EditText в TextView сonClick и отправьте это TextView в просмотр списка

Вот мой XML-файл

    <ListView
        android:id="@+id/results_listview"
        android:layout_width="323dp"
        android:layout_height="369dp"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.58" />

    <Button
        android:id="@+id/AddButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.921"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/results_listview"
        app:layout_constraintVertical_bias="0.084" />

    <EditText
        android:id="@+id/taskText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/enter_task_title"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/results_listview"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.243"

    <EditText
        android:id="@+id/descriptionText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/enter_description"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/results_listview"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/taskText"

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorAccent"
        android:textSize="21sp"
        />

    <TextView
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimary"
        android:textSize="16sp" />


Это моя основная деятельность

Я попробовал много разных предложений на пост других, но ни одинбыли успешными.Я чувствую, что могу упустить что-то очевидное.

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

        final EditText taskText = (EditText) findViewById(R.id.taskText);
        final EditText descText = (EditText) findViewById(R.id.descriptionText);
        final TextView text1 = (TextView) findViewById(R.id.text1);
        final TextView text2 = (TextView) findViewById(R.id.text2);
        Button AddButton = (Button) findViewById(R.id.AddButton);
        final ListView resultsListView = (ListView) findViewById(R.id.results_listview);


        final HashMap<String, String> nameAddresses = new HashMap<>();
        nameAddresses.put("item", "Subitem");
        nameAddresses.put("fgfdg", "fgdg");


        final List<HashMap<String, String>> listItems = new ArrayList<>();
        final SimpleAdapter adapter = new SimpleAdapter(this, listItems, R.layout.list_item,
                new String[]{"First Line", "Second Line"},
                new int[]{R.id.text1, R.id.text2});

        final SimpleAdapter adapter1 = new SimpleAdapter(this, listItems, R.layout.list_item,
                new String[]{"First Line", "Second Line"},
                new int[]{R.id.taskText, R.id.descriptionText});

        final Iterator it = nameAddresses.entrySet().iterator();
        while (it.hasNext())
        {
            HashMap<String, String> resultsMap = new HashMap<>();
            Map.Entry pair = (Map.Entry)it.next();
            resultsMap.put("First Line", pair.getKey().toString());
            resultsMap.put("Second Line", pair.getValue().toString());
            listItems.add(resultsMap);
        }
        resultsListView.setAdapter(adapter);


        AddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String task = taskText.getText().toString();
                String description = descText.getText().toString();

                HashMap<String, String> nameAddresses = new HashMap<>();
                nameAddresses.put("task", "description");

                nameAddresses.put(task, description);


                resultsListView.setAdapter(adapter1);
                adapter1.notifyDataSetChanged();
                //listItems.add(adapter);

            }

        });

    }
}

1 Ответ

0 голосов
/ 03 февраля 2019

Вам необходимо сохранить список всех элементов, которые вы хотите использовать в адаптере, сейчас вы не добавляете новые значения в список адаптеров

HashMap<String, String> nameAddresses = new HashMap<>();
            nameAddresses.put("task", "description");

            nameAddresses.put(task, description);


            resultsListView.setAdapter(adapter1);
            adapter1.notifyDataSetChanged();

Этот код не касается списка адаптерови, следовательно, не добавляет его в список.

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

 list.put(“new”, “item”); 
adapter.notifyDataSetChanged();

Поскольку список связан с адаптером, он будет перерисовывать список элементов, который у него был ранее (который является«Список»), поэтому нет необходимости создавать новые списки или новые адаптеры

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...