将文本从EditText复制到ListView

时间:2013-07-19 14:08:29

标签: android

我想知道如何使用按钮从EditText获取文字,并将其放在ListView中。我试过这段代码:

public class MainActivity extends Activity {
    Button send;
    EditText textBox;

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

        send = (Button) findViewById(R.id.sendBtn);
        textBox = (EditText) findViewById(R.id.textBox);

        EditText text = (EditText) findViewById(R.id.textBox);
        String textBox = text.getText().toString();

        String arr[] = {};

        lv = (ListView) findViewById(R.id.list);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
                                                                R.layout.activity_main, arr);

        lv.setAdapter(adapter);
        textBox.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {}
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

2 个答案:

答案 0 :(得分:0)

Button send;
EditText textBox;

private ArrayAdapter<String> adapter;

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

    send = (Button) findViewById(R.id.sendBtn);
    textBox = (EditText) findViewById(R.id.textBox);

    EditText text = (EditText) findViewById(R.id.textBox);
    String textBox = text.getText().toString();

    String arr[] = {};

    lv = (ListView) findViewById(R.id.list);

    adapter = new ArrayAdapter<String>(getApplicationContext(),
        R.layout.activity_main, arr);

    lv.setAdapter(adapter);
    send.setOnClickListener(new OnClickListener()
    {

        public void onClick(View arg0)
        {
            adapter.add(textBox.getText().tostring());
            adapter.notifyDataSetChanged(); 
        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

答案 1 :(得分:0)

首先,为Button设置OnClickListener。在该听众中,通过EditText抓取textBox.getText().toString()中的文字。接下来,您要使用新选择的文本更新ListView的列表适配器。有很多方法可以做到这一点

  • 更新适配器并通知ListView更改
  • 重建Strings数组并再次为ListView设置适配器