我试着在列表中显示结果

时间:2015-11-03 12:07:51

标签: java android arrays

这是我的代码。我试图从编辑文本中将数据导入数组并尝试在列表视图中显示

    EditText listInput;
    Button listButton;
    ListView listView;
    List<String> names = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listInput = (EditText)findViewById(R.id.listInput);
        listButton = (Button)findViewById(R.id.listButton);
        listView = (ListView)findViewById(R.id.listView);

        listButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addNames();
                ArrayAdapter arrayAdaptor = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,names);
                listView.setAdapter(arrayAdaptor);
            }
        });
    }
    public void addNames(){
        String name = listInput.getText().toString();
        names.add(name);
        Log.d("Entered text is" ,name);
    }
}

1 个答案:

答案 0 :(得分:0)

每次都在创建适配器

使用此

    EditText listInput;
    Button listButton;
    ListView listView;
    ArrayAdapter arrayAdaptor;
    List<String> names = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listInput = (EditText)findViewById(R.id.listInput);
        listButton = (Button)findViewById(R.id.listButton);
        listView = (ListView)findViewById(R.id.listView);

        listButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addNames();
                if(arrayAdaptor == null){
                arrayAdaptor = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,names);
                listView.setAdapter(arrayAdaptor);
                }else{
                arrayAdaptor.notifyDataSetChanged();
                }
            }
        });
    }
    public void addNames(){
        String name = listInput.getText().toString();
        names.add(name);
        Log.d("Entered text is" ,name);
    }
}