如何从AutoCompleteTextView中选取文本并将其显示在ListView中?

时间:2019-06-10 08:27:14

标签: java android android-layout android-linearlayout

public class MainActivity extends AppCompatActivity {
AutoCompleteTextView et;
Button bt;
ListView lt;
ArrayList<Double> addArray = new ArrayList<Double>();
String getInput;
double sum = 0;

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

///创建了用于显示列表的适配器,R.array.veggi是一个包含植物名称的资源文件

    String[] veggi = getResources().getStringArray(R.array.veggi);
    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, veggi);
    lt.setAdapter(adapter1);

    et = (AutoCompleteTextView) findViewById(R.id.Et);
    bt = (Button) findViewById(R.id.bt);
    lt =  (ListView)findViewById(R.id.listview);



    // btton to show text or numbers entered in AutoCompleteTextView
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getInput = et.getText().toString();
             double inp = Double.parseDouble(getInput);

            if (addArray.contains(getInput)) {
                Toast.makeText(getBaseContext(), "Item Already Added to array", Toast.LENGTH_SHORT).show();
            } else if (getInput == null || getInput.trim().equals(" ")) {
                Toast.makeText(getBaseContext(), "Input field is Empty", Toast.LENGTH_SHORT).show();

            } else {
                addArray.add(inp);
                ArrayAdapter<Double> adapter = new ArrayAdapter<Double>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
                lt.setAdapter(adapter);


                ((AutoCompleteTextView) findViewById(R.id.Et)).setText(" ");
            }
        }
    });       
  }
}

//创建了用于显示列表的适配器,如果我删除此代码,它将显示在LisView中输入的文本,但我想显示建议并像google搜索kindof那样从中选择单词

String[] veggi = getResources().getStringArray(R.array.veggi);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, veggi);
        lt.setAdapter(adapter1);

1 个答案:

答案 0 :(得分:0)

问题在这里

 ArrayList<Double> addArray = new ArrayList<Double>();
 ArrayAdapter<Double> adapter = new ArrayAdapter<Double>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);

将其更改为...

ArrayList<String> addArray = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);