首页 > 解决方案 > 将文本打印到列表视图,从对话框输入

问题描述

我有关于代码的情况。我找不到解决方案,因为我是这方面的初学者。

我有 3 个片段,每个片段都有列表视图的框架。你可以在这里查看面板。

我有一个导航菜单,上面有一个“添加任务”按钮。此按钮打开一个对话框,当我单击“确定”时,对话框需要一个文本(问题从这里开始)写入“todotasks_frame.xml”中的列表视图(id = listview1)。但我做不到。

我的 MainActivity 代码

package com.example.lenovo.myapplication;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    ArrayList<String> todotasks_frame,completedtasks_frame,alltasks_frame;
    ArrayAdapter<String> todotasks_frameAdapter,completedtasks_frameAdapter,alltasks_frameAdapter;

    AlertDialog dialog;
    AlertDialog.Builder builder;

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



        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        FragmentToDoTasks fragmentToDoTasks=new FragmentToDoTasks();
        ft.add(R.id.content_frame,fragmentToDoTasks);
        ft.commit();



        todotasks_frame=new ArrayList<>();
        todotasks_frameAdapter = new ArrayAdapter<>(this, R.layout.simplerow, todotasks_frame);
        completedtasks_frame=new ArrayList<>();
        completedtasks_frameAdapter =new ArrayAdapter<>(this, R.layout.simplerow, completedtasks_frame);
        alltasks_frame=new ArrayList<>();
        alltasks_frameAdapter =new ArrayAdapter<>(this, R.layout.simplerow, alltasks_frame);



        builder = new AlertDialog.Builder(this);
        builder.setTitle("Add a Task");
        final EditText input = new EditText(this);
        builder.setView(input);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which){
               /* Problem area :,( */

            }
        });
        builder.setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
                dialog.dismiss();
            }
        });
        dialog=builder.create();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        int id = item.getItemId();

        if (id == R.id.main_todo_tasks) {
            FragmentToDoTasks fragmentToDoTasks = new FragmentToDoTasks();
            ft.replace(R.id.content_frame, fragmentToDoTasks);
            ft.commit();

        } else if (id == R.id.main_completed_tasks) {
            FragmentCompletedTasks fragmentCompletedTasks = new FragmentCompletedTasks();
            ft.replace(R.id.content_frame, fragmentCompletedTasks);
            ft.commit();

        } else if (id == R.id.main_all_tasks) {
            FragmentAllTasks fragmentAllTasks = new FragmentAllTasks();
            ft.replace(R.id.content_frame, fragmentAllTasks);
            ft.commit();

        } else if (id == R.id.main_close) super.onBackPressed();

        return true;

    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {


        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        int id = item.getItemId();
        if (id == R.id.nav_add_tasks) {
            dialog.show();

        } else if (id == R.id.nav_todo_tasks) {
            FragmentToDoTasks fragmentToDoTasks = new FragmentToDoTasks();
            ft.replace(R.id.content_frame, fragmentToDoTasks);
            ft.commit();

        } else if (id == R.id.nav_completed_tasks) {
            FragmentCompletedTasks fragmentCompletedTasks = new FragmentCompletedTasks();
            ft.replace(R.id.content_frame, fragmentCompletedTasks);
            ft.commit();

        } else if (id == R.id.nav_all_tasks) {
            FragmentAllTasks fragmentAllTasks = new FragmentAllTasks();
            ft.replace(R.id.content_frame, fragmentAllTasks);
            ft.commit();
        } else if (id == R.id.nav_exit) super.onBackPressed();

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

标签: android

解决方案


考虑到您的问题,我创建了一个演示项目我所做的是我创建了 10 个虚拟项目的回收器视图,之后当您添加新任务时,有一个添加新任务的按钮,它很容易添加到列表中并且列表得到轻松更新新条目。YOUR_LIST_NAME.clear()成功的关键是除了onCreate()方法之外不要在任何地方使用

希望此代码将帮助您理解notifyDataSetChanged();调用它的值,studentAdapter它只是使用列表中所做的更改来更新列表,例如从列表中添加、删除。

NewMainActivity.class

public class NewMainActivity extends AppCompatActivity {
RecyclerView recycle;
StudentAdapter studentAdapter;
Button addNewButton;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_new);
    recycle = findViewById(R.id.recycle);
    addNewButton = findViewById(R.id.addNewButton);
    setListeners();

    listing.clear();
    produceList();

}

AlertDialog.Builder builder;
ArrayList<StudentModel> listing = new ArrayList<>();

private void produceList() {
    for (int k = 0; k < 10; k++) {
        StudentModel studentModel = new StudentModel();
        studentModel.setName(k + " Task");
        listing.add(studentModel);
    }
    Collections.reverse(listing);
    studentAdapter = new StudentAdapter(NewMainActivity.this, listing);
    recycle.setNestedScrollingEnabled(false);
    recycle.setLayoutManager(new LinearLayoutManager(this));
    recycle.setAdapter(studentAdapter);
    studentAdapter.notifyDataSetChanged();
}

public void setListeners() {
    addNewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            builder = new AlertDialog.Builder(NewMainActivity.this);
            builder.setTitle("Add a Task");
            final EditText input = new EditText(NewMainActivity.this);
            builder.setView(input);
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String name = input.getText().toString();
                    StudentModel studentModel = new StudentModel();
                    studentModel.setName(name);
                    listing.add(studentModel);
                    Collections.reverse(listing);
                    studentAdapter.notifyDataSetChanged();
                }
            });
            builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();

        }
    });
}

}

activity_main_new.xml

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

<Button
    android:id="@+id/addNewButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add New" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycle"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

回收者视图适配器的单个项目

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="20dp"
    android:text="name" />

StudentAdapter.class

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {
ArrayList<?> notificationListData;
Context context;

public StudentAdapter(Context context, ArrayList<?> notificationListData) {
    this.context = context;
    this.notificationListData = notificationListData;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_studenyt, parent, false);
    return new MyViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    if (notificationListData.get(position) instanceof StudentModel) {
        holder.name.setText(((StudentModel) notificationListData.get(position)).getName());
    }
}

@Override
public int getItemCount() {
    return notificationListData.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView name;

    public MyViewHolder(View itemView) {
        super(itemView);
        name = itemView.findViewById(R.id.name);
    }
}

}

StudentModel.class

public class StudentModel  {
private String name;
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

推荐阅读