[英]How to get the view which triggered the event in Android?
你知道我怎样才能获得触发事件的视图吗? 举例:
final AutoCompleteTextView edtxInput = (AutoCompleteTextView)layout.findViewById(R.id.edtx_input);
edtxInput.setThreshold(2);
edtxInput.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
Console.debug(TAG, "view: " + arg1, Console.Liviu);
edtxInput.setText(((FormOption)edtxInput.getAdapter().getItem(position)).getDescription());
}
});
这里的问题是我不知道如何在 OnItemClickListener 中更新来自 edtxInput 的文本而不使其成为最终文本。
谢谢
检查这个http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
参数
parent 发生点击的 AdapterView。
arg1 是 AutoCompleteTextView (edtxInput) 本身。 所以你可以做
AutoCompleteTextView edtxInput = (AutoCompleteTextView)layout.findViewById(R.id.edtx_input);
edtxInput.setThreshold(2);
edtxInput.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
Console.debug(TAG, "view: " + arg1, Console.Liviu);
AutoCompleteTextView medtxInput = (AutoCompleteTextView)parent;
medtxInput.setText(((FormOption)medtxInput.getAdapter().getItem(position)).getDescription());
}
});
更新
似乎AutoCompleteTextView
不是 AdapterView 的子类。 这在某种程度上是 SDK 的“错误”。 要获得AutoCompleteTextView
你可以做一个黑客
AutoCompleteTextView medtxInput = (AutoCompleteTextView)view.getParent();
所以你得到点击的视图,然后得到它的父视图,即AutoCompleteTextView
但是为什么您首先不希望AutoCompleteTextView
成为最终结果? 有什么特别的原因吗?
如果你只想要适配器,你可以写这个,只有这个
((ChildClass)parent.getItemAtPosition(position)).getDescription();
将 edtxInput 声明为全局变量,以便在整个类中可以访问该变量。
为什么使变量 final 对您如此不利? 您可以通过任何方式使 edtxInput 全局化。 见下面的代码
public class myActivity extends Activity implements OnItemClickListener {
AutoCompleteTextView mEditTextInput;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEditTextInput = (AutoCompleteTextView)layout.findViewById(R.id.edtx_input);
mEditTextInput.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
Console.debug(TAG, "view: " + arg1, Console.Liviu);
mEditTextInput.setText(((FormOption)mEditTextInput.getAdapter().getItem(position)).getDescription());
}
}
就这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.