从 android 中的 Multiautocomplete 向数组添加值

Adding values to array from the Multiautocomplete in android

如何使用 MultiAutoCompleteTextView 从用户那里获取多个条目,以便将每个条目添加到单独的字符串中,并且每个字符串都应存储在字符串数组中。

@威廉·威利

检查下面

您将需要使用 split() 方法,因为我们使用 CommaTokenizer() 作为我们的 MultiAutoCompleteTextView

所以你的布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="iifl.animesh.cuser.progressbarexample.MainActivity">

    <MultiAutoCompleteTextView
        android:id="@+id/multitoken"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/submit"
        android:layout_below="@+id/multitoken"
        android:text="Submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


</RelativeLayout>

在你的 mainActivity 中

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private MultiAutoCompleteTextView multiAutoCompleteTextView;

    // your array for the autocomplete

    private static final String[] COUNTRIES = new String[] {
            "India","Belgium", "France", "Italy", "Germany", "Spain","USA","China"
    };

    private Button mbutton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        multiAutoCompleteTextView = (MultiAutoCompleteTextView) findViewById(R.id.multitoken);
        mbutton = (Button) findViewById(R.id.submit);

        // setting listener for button
        mbutton.setOnClickListener(this);

        //setting adapter for multiAutoCompleteTextView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, COUNTRIES);
        multiAutoCompleteTextView.setAdapter(adapter);
        multiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());


    }

    @Override
    public void onClick(View view) {
        String text = multiAutoCompleteTextView.getText().toString();

        if(text != null && text.length() >0) {
            text = text.substring(0, text.length() - 1);
        String countries[] = text.split(",");  // countries array will have all the countries entered in multiAutoCompleteTextView

        for(String s : countries) {
            Toast.makeText(this,"Countries are = "+s,Toast.LENGTH_SHORT).show();
        }
        }
        else {
           Toast.makeText(this,"Please enter text",Toast.LENGTH_SHORT).show();
       }

    }
}

希望对您有所帮助