我有一個定製的小部件,它擴展了線性佈局。 它只是利用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