quiero aplicar un evento onClickListener a un imageView, ¿cómo lo logro? ¿Alguien puede proporcionarle algunos ejemplos de código fuentecómo aplicar click oyente de eventos a la imagen en android
29
A
Respuesta
75
ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your code here
}
});
24
En xml:
<ImageView
android:clickable="true"
android:onClick="imageClick"
android:src="@drawable/myImage">
</ImageView>
En el código
public class Test extends Activity {
........
........
public void imageClick(View view) {
//Implement image click function
}
1
probar este ejemplo.
activity_main.xml:
<LinearLayout 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"
tools:context=".MainActivity" >
<GridView
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/grid"
android:background="#fff7ff"
/>
</LinearLayout>
grid_single.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="@+id/grid_image"
android:layout_width="60dp"
android:layout_height="60dp"
>
</ImageView>
<TextView
android:id="@+id/grid_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textSize="9sp"
android:textColor="#3a0fff">
</TextView>
</LinearLayout>
CustomGrid.java:
package com.example.lalit.gridtest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final String[] web;
private final int[] Imageid;
public CustomGrid(Context c, String[] web, int[] Imageid) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return web.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
textView.setText(web[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
MainActivity.java:
package com.example.lalit.gridtest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
GridView grid;
String[] web = {
"Mom",
"Mahendra",
"Narayan",
"Bhai",
"Deepak",
"Sanjay",
"Navdeep",
"Lovesh",
};
int[] imageId = {
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id){
if (web[position].toString().equals("Mom")) {
try {
String uri ="te:"+ "9009388988";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if (web[position].toString().equals("Mahendra")) {
try {
String uri = "tel:" + "99669660948";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Narayan")){
try {
String uri = "tel:" + "8889115906";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Bhai")){
try {
String uri = "tel:" + "9893352005";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Deepak")){
try {
String uri = "tel:" + "7869302868";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Sanjay")){
try {
String uri = "tel:" + "9584124849";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Navdeep")){
try {
String uri = "tel:" + "8602475687";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Lovesh")){
try {
String uri = "tel:" + "8871512449";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
});
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lalit.gridtest" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Cuestiones relacionadas
- 1. OnClick oyente a una imagen ListView - Android
- 2. Oyente de eventos personalizados de Android
- 3. ¿Cómo implementar el oyente táctil en la imagen?
- 4. ¿Cómo se configura el oyente click para notificación?
- 5. Oyente para widget de ViewFlipper voltear eventos
- 6. Button Click Event en Android
- 7. Cómo aplicar a la imagen personalizada casilla de verificación androide
- 8. Oyente de red Android
- 9. Cómo eliminar todos los controladores de eventos Click en Jquery
- 10. ¿Cómo agrego un evento .click() a una imagen?
- 11. AutoCompleteTextView evento click en Android
- 12. Parada del oyente en Android
- 13. escuchando múltiples eventos con un solo oyente?
- 14. Android, oyente Checkbox en XML?
- 15. Oyente HTML5 EventSource para todos los eventos?
- 16. Cómo determinar el oyente de pulsación larga en la vista de imagen?
- 17. ¿Cómo eliminar todos los controladores de eventos Click?
- 18. eventos táctiles vs eventos mouse click usando actionscript 3
- 19. android cómo hacer oyente a una variable personalizada?
- 20. Oyente para Fin de llamada en Android
- 21. byte [] a la imagen android
- 22. Oyente de Internet Ejemplo de Android
- 23. cómo aplicar el efecto sobre la imagen en Android como distorsionar, foco, exposición y muchos más
- 24. OpenCV - Aplicar máscara a una imagen en color
- 25. bytes Android [] a la imagen en Camera.onPreviewFrame
- 26. ¿Cómo crear un oyente para eventos de Git a través del complemento de EGit/JGit?
- 27. ¿Cómo aplicar dos estilos diferentes a un elemento en Android?
- 28. Cómo agregar efectos de imagen en android?
- 29. android widget on click event
- 30. Javascript: Adjuntar al oyente de eventos a la matriz para el evento Push()
múltiples marcadores en esta línea \t - El método setOnClickListener (View.OnClickListener) en el tipo de vista no es aplicable para los argumentos (nueva DialogInterface.OnClickListener() {}) \t - El tipo nuevo DialogInterface.OnClickListener() {} debe implementar el método abstracto heredado DialogInterface.OnClickListener.onClick (DialogInterface, \t int) – Jaseem
@Jaseem: Parece que tiene 'imports' que hace que el compilador interprete' OnClickListener' como un 'DialogInterface.OnClickListener'. Intente especificar explícitamente '(new View.OnClickListener() {...});' –
Creo que la solución que se muestra a continuación es mejor. Configurar 'android: onClick =" imageClick "' en el XML parece más fácil de entender. La solución LIKE anterior funciona de forma brillante en la web y JavaScript. Parece que Java está intentando copiar JavaScript. Nunca será tan bueno. – Jaseem