use*_*716 8 android android-spinner
我在Android应用程序中使用微调控件,我通过onItemSelectedListener()方法处理用户选择.当与当前选项不同时,这似乎可以正常工作.我想在某些条件下将所有微调器重置为默认值并确保onItemSelectedListener()为所有调整器调用.
它是Android的语义的一部分,onItemSelectedListener()仅在用户选择更改时调用.有没有办法强制onItemSelectedListener()被召唤?
Jer*_*ham 12
如果要激活Spinner的"onItemSelected",即使选择了微调器中的项目/选择了项目并再次单击它.然后使用这个扩展微调器的自定义类,这对我有用
然后用像这样的微调器编辑你的活动,我改变了
static Spinner spinner1;
Run Code Online (Sandbox Code Playgroud)
至
static NDSpinner spinner1;
Run Code Online (Sandbox Code Playgroud)
和
variables.spinner1 = (Spinner) findViewById(R.id.spinner1);
Run Code Online (Sandbox Code Playgroud)
至
variables.spinner1 = (NDSpinner ) findViewById(R.id.spinner1);
Run Code Online (Sandbox Code Playgroud)
我还改变了微调器所在的xml布局
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/place" />
Run Code Online (Sandbox Code Playgroud)
至
<com.yourpackagename.NDSpinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/place" />
Run Code Online (Sandbox Code Playgroud)
Spinner扩展类:
package com.yourpackagename;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Spinner;
import android.widget.Toast;
import java.lang.reflect.Field;
/** Spinner extension that calls onItemSelected even when the selection is the same as its previous value.
* ie This is extended "Customized class of Spinner" to get the "onItemSelected" event even if the item in the
* Spinner is already selected by the user*/
public class NDSpinner extends Spinner {
public NDSpinner(Context context)
{ super(context); }
public NDSpinner(Context context, AttributeSet attrs)
{ super(context, attrs); }
public NDSpinner(Context context, AttributeSet attrs, int defStyle)
{ super(context, attrs, defStyle); }
private void ignoreOldSelectionByReflection() {
try {
Class<?> c = this.getClass().getSuperclass().getSuperclass().getSuperclass();
Field reqField = c.getDeclaredField("mOldSelectedPosition");
reqField.setAccessible(true);
reqField.setInt(this, -1);
} catch (Exception e) {
Log.d("Exception Private", "ex", e);
// TODO: handle exception
}
}
@Override
public void setSelection(int position, boolean animate)
{
boolean sameSelected = position == getSelectedItemPosition();
ignoreOldSelectionByReflection();
super.setSelection(position, animate);
if (sameSelected) {
// Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
}
}
@Override
public void setSelection(int position) {
ignoreOldSelectionByReflection();
super.setSelection(position);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6902 次 |
| 最近记录: |