我有一个包含内部(子)自定义图像视图的线性布局。
我的目标是在图像视图上设置一个背景选择器,并为线性布局设置一个监听器。
但是,我不能让选择器和监听器一起工作。我不知道如何处理这些事件。
如果我快速点击它正在工作,但如果我在视图上拖动手指,图像视图仍处于选定状态。
这是引用线性布局及其侦听器的活动。
public class EventDispatchingDemoActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.my_layout);
linearLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Click", Toast.LENGTH_SHORT).show();
}
});
}
}
这是自定义视图(这是我在某处找到的代码,归功于作者)
public class ImageSelector extends ImageView
{
public ImageSelector(Context context, AttributeSet attrs)
{
super(context, attrs);
setBackgroundDrawable(new NavStateListDrawable(getContext(), 0));
setClickable(true);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
super.onTouchEvent(event);
return false;
}
public class NavStateListDrawable extends StateListDrawable
{
private int level;
public NavStateListDrawable(Context context, int level)
{
this.level = level;
// int stateChecked = android.R.attr.state_checked;
int stateFocused = android.R.attr.state_focused;
int statePressed = android.R.attr.state_pressed;
int stateSelected = android.R.attr.state_selected;
addState(new int[] { stateSelected }, context.getResources().getDrawable(R.drawable.slide_feedback));
addState(new int[] { statePressed }, context.getResources().getDrawable(R.drawable.slide_feedback));
addState(new int[] { stateFocused }, context.getResources().getDrawable(R.drawable.slide_feedback));
addState(new int[] { -stateFocused, -statePressed, -stateSelected }, context.getResources().getDrawable(android.R.color.transparent));
}
@Override
protected boolean onStateChange(int[] stateSet)
{
boolean nowstate = super.onStateChange(stateSet);
try
{
LayerDrawable defaultDrawable = (LayerDrawable) this.getCurrent();
LevelListDrawable bar2 = (LevelListDrawable) defaultDrawable.findDrawableByLayerId(R.id.element_contact_image_selector);
bar2.setLevel(level);
}
catch (Exception exception)
{
}
return nowstate;
}
}
}
这是xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#acf1fa"
android:gravity="center"
android:orientation="vertical" >
<!-- outer layout -->
<LinearLayout
android:id="@+id/my_layout"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#00ff00"
android:gravity="center" >
<!-- inner layout -->
<dor.event.dispathing.ImageSelector
android:id="@+id/inner_layout"
android:layout_width="150dp"
android:layout_height="150dp" />
</LinearLayout>
</LinearLayout>
我上传了源码: http ://www.filefactory.com/file/5ikfwyk9j5bx/n/EventDispatchingDemo.rar
在此先感谢您的帮助!