gpt4 book ai didi

Android:永远不会调用 onTouch()?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:11:31 26 4
gpt4 key购买 nike

我正在玩 UI 事件处理,我发现了一些我无法从 Android Dev 中找到解释的东西:我有一个 ImageView 和一个 TextView,每当我触摸 ImageView 时,TextView 都会显示一条消息。但以下代码不起作用:

    public class ShowSomething extends Activity {
private LinearLayout ll;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout);
final TextView textview = (TextView)findViewById(R.id.textview);
MyImageView image = new MyImageView(this, textview);
image.setImageResource(R.drawable.icon);
ll.addView(image, 48, 48);

}
}

和MyImageView.java

public class MyImageView extends ImageView implements OnTouchListener{


private TextView textview;

public MyImageView(Context context,TextView textview) {
super(context);
this.textview = textview;
}

@Override
public boolean onTouch(View v, MotionEvent event) {
textview.setText("Event captured !");
return true;
}
}

主.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Holder"
/>
</LinearLayout>

但是当我像这样在 MyImageView 上附加一个 OnTouchListener 时,它确实有效:文件 ShowSomething.java

public class ShowSomething extends Activity {

private LinearLayout ll;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout);
final TextView textview = (TextView)findViewById(R.id.textview);


MyImageView image = new MyImageView(this,textview);
image.setImageResource(R.drawable.icon);
image.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
textview.setText("Event captured!");
return false;
}
});
ll.addView(image, 48, 48);

}

}

和文件 MyImageView.java

public class MyImageView extends ImageView { 


private TextView textview;

public MyImageView(Context context,TextView textview) {
super(context);
this.textview = textview;
}


}

但据我所知,2 的实现是相同的(实现一个事件监听器)——我有没有误解什么?

最佳答案

您的第一个实现忘记设置监听器...在 MyImageView 构造函数中调用 setOnTouchListener(this) 它应该可以工作。

关于Android:永远不会调用 onTouch()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com