【发布时间】:2014-09-03 12:13:46
【问题描述】:
我有一个扩展线性布局的自定义小部件。 它只是一小段文字。
这是小部件的 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>
如果我在 Activity 的某处为该自定义小部件创建 onClickListener - 只有当我单击该布局中的最后一个 TextView 时它才会做出反应。但我需要为包含“标题”textView 的水平LinearLayout 设置onClickListener,或者直接在标题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);
}
}
感谢您的回答。
【问题讨论】:
-
所以我通过创建自定义事件监听器来解决这个问题。 stackoverflow.com/questions/8292712/…
标签: java android widget listener