我在操作栏中有一个下拉AutoCompleteTextView。
我正在尝试从AutoCompleteTextView获取文本并将其存储到字符串中。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location2);//Location2 is my layout
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.location, null);//location is my custom action bar
actionBar.setCustomView(view);
Global global = new Global();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, global.getUniversities());
AutoCompleteTextView textView = (AutoCompleteTextView) view
.findViewById(R.id.searchLocation);
textView.setAdapter(adapter);
...
}
public void changeLocation(View view){
View v = View.inflate(this, R.layout.location, null);
AutoCompleteTextView searchLocation = (AutoCompleteTextView)
v.findViewById(R.id.searchLocation);
String searchLocationText = searchLocation.getText().toString();
Toast.makeText(this, searchLocationText,
Toast.LENGTH_LONG).show();
...
}
<AutoCompleteTextView
android:id="@+id/searchLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:drawableLeft="@drawable/search"
android:paddingTop="15dp"
android:imeOptions="actionSearch"
android:inputType="textAutoComplete|textAutoCorrect"
android:textColor="#FFFFFF" >
<requestFocus />
</AutoCompleteTextView>
自动完成功能就像一个魅力......但是toast显示String searchLocationText是空的......
操作栏中的autocompletetextview有什么不正确的地方?
如何将文本转换为字符串?
编辑: - 更多详情
我可以输入AutoCompleteTextView,它会自动填充下拉列表,一切正常。但我尝试将该信息转换为字符串,字符串为空......
错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.AutoCompleteTextView.getText()' on a null object reference
错误指的是行:
String searchLocationText = searchLocation.getText().toString();
答案 0 :(得分:1)
您需要从已附加到布局的视图中获取文本。但是你在这里夸大了一个新观点。
public void changeLocation(View view) {
View v = View.inflate(this, R.layout.location, null);
AutoCompleteTextView searchLocation = (AutoCompleteTextView)
v.findViewById(R.id.searchLocation);
String searchLocationText = searchLocation.getText().toString();
Toast.makeText(this, searchLocationText,
Toast.LENGTH_LONG).show();
[...]
}
而是在onCreate()
public void changeLocation(View view) {
ActionBar actionBar = getSupportActionBar();
view = actionBar.getCustomView();
AutoCompleteTextView searchLocation = (AutoCompleteTextView) view
.findViewById(R.id.searchLocation);
String searchLocationText = searchLocation.getText().toString();
Toast.makeText(this, searchLocationText,
Toast.LENGTH_LONG).show();
[...]
}