我有一个定制的小部件,它扩展了线性布局。 它只是利用litle的文本块。在自定义小部件中自定义onClickListner - 如何?
这里是小工具的XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:background="@drawable/actionbar_background"
android:layout_height="35dp"
android:paddingLeft="15dp"
android:gravity="center_vertical">
<TextView
android:id="@+id/title"
android:layout_height="35dp"
android:textColor="@color/white"
android:layout_width="match_parent"
android:textSize="18dp"
android:clickable="true"
android:gravity="center_vertical" />
</LinearLayout>
<TextView
android:id="@+id/ingreds"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Some text"
android:paddingLeft="15dp" />
</LinearLayout>
如果我创造onClickListener
为自定义部件在Activity
的地方 - 它只有当我在布局点击最后TextView
反应。但我需要设置onClickListener水平LinearLayout
其中包含“title”textView,或直接在标题TextView上。 重要提示:我想要设置这些听众OUTSIDE自定义控件类。
我认为我需要覆盖setOnclickListener
方法在我的自定义类或类似的东西,但我不知道它是如何做到的。
这里是类自定义部件的:
public class MyTextBlock extends LinearLayout {
private TextView title;
private TextView ingreds;
public MyTextBlock(Context context) {
this(context, null);
}
public MyTextBlock(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.my_text_block, this, true);
title = (TextView) findViewById(R.id.title);
ingreds = (TextView) findViewById(R.id.ingreds);
}
public void setText(String text) {
ingreds.setText(text);
}
public void setTitle(String titleText) {
title.setText(titleText);
}
}
谢谢回答。
所以我通过创建自定义事件侦听器来解决这个问题。 http://stackoverflow.com/questions/8292712/android-custom-event-listener/8293106#8293106 – udenfox 2014-09-04 13:24:05