0
我想使用AutoCompleteTextView
使用自定義ArrayAdapter
。我決定使用Arrayadapter
。在Android中未調用AutoCompleteTextView的自定義ArrayAdapter getView?
但是在我的自定義ArrayAdapter
getView()
未被調用,AutoCompleteTextView
未由適配器設置。
下面一個可以看到我試過到目前爲止:
MainActivity.java
:
public class MainActivity extends AppCompatActivity {
AutoCompleteTextView text;
String[] languages = { "Android ", "java", "IOS", "SQL", "JDBC", "Web services" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Names[] names = this.initNameArray();
this.text = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
this.text.setThreshold(1);
adapter adapter = new adapter(this, R.layout.recent_text, names);
this.text.setAdapter(adapter);
}
private Names[] initNameArray() {
Names[] recent_search = new Names[this.languages.length];
int i = 0;
for (String s : this.languages) {
Names names = new Names();
names.setName(s);
recent_search[i++] = names;
}
return recent_search;
}
// custom adapter
public class adapter extends ArrayAdapter<Names> {
Names names[];
Context context;
int layoutResourceId;
public adapter(Context context, int resource, Names[] objects) {
super(context, resource, objects);
this.names = objects;
this.context = context;
this.layoutResourceId = resource;
}
@Override
public int getCount() {
return this.names.length;
}
@Override
public Names getItem(int position) {
return this.names[position];
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
/*
* The convertView argument is essentially a "ScrapView" as
* described is Lucas post
* http://lucasr.org/2012/04/05/performance-tips-for-androids-
* listview/ It will have a non-null value when ListView is
* asking you recycle the row layout. So, when convertView is
* not null, you should simply update its contents instead of
* inflating a new row layout.
*/
if (convertView == null) {
// inflate the layout
LayoutInflater inflater = (LayoutInflater) ((this.context))
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(this.layoutResourceId, parent, false);
}
// object item based on the position
Names objectItem = this.getItem(position);
// get the TextView and then set the text (item name) and tag
// (item ID) values
TextView textViewItem = (TextView) convertView.findViewById(R.id.recent_search);
textViewItem.setText(objectItem.getName());
// in case you want to add some style, you can do something
// like:
textViewItem.setBackgroundColor(Color.CYAN);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
// my pojo class
public class Names {
String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
}
你調試了嗎?我的意思是你應該首先在構造函數中放置一個斷點,以便檢查它是否在getView的第一行被調用。 –
是的,我調試它。在調用構造函數之後,我在getview方法的第一行放置了斷點,但沒有調用 –
嘗試使用調試器刪除和添加文本。它應該工作。 –