我在 layouts 文件夹中有一个名为otro_layout_relativo.xml的文件,它包含:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".TimelineActivity" >
<TextView
android:id="@+id/tvOlrTitulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/ivOlrImgPerfil"
android:layout_marginBottom="15dp"
android:layout_toRightOf="@+id/ivOlrImgPerfil"
android:text="Baño de burbujas"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="@+id/ivOlrImgBebe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/ivOlrImgPerfil"
android:layout_alignTop="@+id/tvOlrTitulo"
android:layout_marginLeft="30dp"
android:layout_marginTop="16dp"
android:src="@drawable/imagen_bebe" />
<ImageView
android:id="@+id/ivOlrImgPerfil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="38dp"
android:src="@drawable/foto_perfil_papa" />
<TextView
android:id="@+id/tvOlrFecha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/ivOlrImgPerfil"
android:text="02/28\n1992"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="10sp" />
</RelativeLayout>
在我的MainActivity我有以下内容:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
botAniadir = (Button) findViewById(R.id.botAniadir);
mainLinearLayout = (LinearLayout) findViewById(R.id.main_linear_layout);
for (int i = 0; i < 2; i++) {
relativeLayout = (RelativeLayout) View.inflate(this, R.layout.otro_layout_relativo, null);
((TextView) relativeLayout.findViewById(R.id.tvOlrTitulo)).setText("Elemento " + i);
((ImageView) relativeLayout.findViewById(R.id.ivOlrImgBebe)).setId(i);
ivFoto = (ImageView) relativeLayout.findViewById(R.id.ivOlrImgBebe);
ivFoto.setOnClickListener(new ListenerImagen());
/*ivFoto.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Log.v("TAG", "onClick");
Log.v("ID", String.valueOf(v.getId()));
}
});*/
mainLinearLayout.addView(relativeLayout);
}
我想要做的是将 OnClickListener 设置为 ivFoto 小部件(ImageView)。我尝试将一个类设置为侦听器和一个匿名类,但两者都给了我错误并使应用程序崩溃。
在ListenerImage我有:
public class ListenerImagen implements android.view.View.OnClickListener {
@Override
public void onClick(View v) {
View padre = (View) v.getParent();
if (padre != null) {
Log.v("Listener", "Cliiiiik!");
}
}
}
有什么形式可以做到这一点吗?
问候,亚历克斯。