Comment obtenir l'identifiant d'une image a partir d'un fichier string
Bonsoir tous le monde:P
Voilà j'ai créé un adapter personnalisé pour mon GridView qui va afficher une image d'un livre(image View) et son nom(texte View) ;
, j'ai déclaré la liste des noms des livres dans le fichier string.
Code:
1 2 3 4 5 6 7 8 9 10 11
|
<string-array name="bookLabels">
<item>android security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>security</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker</item>
<!-- <item>Black Hat Python</item>-->
</string-array> |
ce que je veux savoir c'est comment faire la même chose pour les images ie : les déclarer dans array-string:
Code:
1 2 3 4 5 6 7 8 9 10
|
<string-array name="bookImages">
<item>@drawable/android_security</item>
<item>@drawable/penetration_testing</item>
<item>@drawable/red_team</item>
<item>@drawable/security</item>
<item>@drawable/the_art_of_exploitation</item>
<item>@drawable/web_application_hacker </item>
<item>@drawable/bhp </item>
</string-array> |
Au lieu de creer un array dans le code java
Voilà le code complet : j'ai deux fonctions
J'ai essayé de faire la même chose qu'avec les textes View mais ça marche pas.
BookGrid
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
package com.example.gridview.BookGrid;
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;
import com.example.gridview.R;
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
//Resources res = context.getResources();
// String[] bookImages =res.getStringArray(R.array.bookImages);
//je veux le remplacer par :private String[] bookImages; //du res/strings
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.security,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.bhp
};
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return bookImages.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
//To Avoid ArrayIndexOutOfBoundsException
boolean inBounds = (position >= 0) && (position <= imageName.length);
if (!inBounds) {
txtv.setText(imageName[position]);
} else {
String imgname = bookImages[position].toString();
String name = (String) context.getResources().getResourceEntryName(Integer.parseInt(imgname));
txtv.setText(name);
}
imgv.setImageResource(bookImages[position]);
} else {
}
return convertView;
}
} |
et main
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
package com.example.gridview.BookGrid;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.gridview.R;
public class main extends AppCompatActivity {
String[] labels;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Resources res = getResources();
labels = res.getStringArray(R.array.bookLabels);
GridView gridView = findViewById(R.id.gridView1);
BookGrid myAdapter = new BookGrid(getApplicationContext(), labels);
gridView.setAdapter(myAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v.findViewById(R.id.gridtextView))
.getText(), Toast.LENGTH_SHORT).show();
}
});
}
} |
j'espère que j'étais un peu clair ;
Merci d'avance:D
Optimisation de la methode getImageId
Citation:
Envoyé par
Turvy
As tu essayé de remplacer "R.drawable.android.png" juste par "android" ?
Merci Turvy :ptdr: oui c'était ça l'astuce (déclarer le nom de la variable sans l'extention)
Donc voilà les démarches suivis:
1==> J'ai déclaré les images dans un fichier String
Code:
1 2 3 4 5 6 7 8 9 10
| <string-array name="bookImages">
<item>@drawable/android_security</item>
<item>@drawable/penetration_testing</item>
<item>@drawable/red_team</item>
<item>@drawable/lf</item>
<item>@drawable/the_art_of_exploitation</item>
<item>@drawable/web_application_hacker </item>
<item>@drawable/lbh </item>
<item>@drawable/bhp </item>
</string-array> |
2==> J'ai récupéré ce tableau String
Code:
1 2 3 4 5 6
| //declaration
private String[] bookImagesFromStringArray;
//récupération
Resources res = context.getResources();
bookImagesFromStringArray = res.getStringArray(R.array.bookImages); |
3==> J'ai supprimé res/drawable/ et (png || jpg) de chaque image
4==> J'ai utilisé la méthode getIdentifier pour trouver l'Id de chaque Image
5==> Retourner un tableau des IDs
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public static Integer[] getImageId(String[] str, Context context) {
String[] imageName = new String[str.length];//table that contains the names of the image
Integer[] imageNameInt = new Integer[str.length];//table that contains IDs for each image
//words to delete
String remove1 = "res/drawable-v24/";
String remove2 = "res/drawable/";
String remove3 = ".png";
String remove4 = ".jpg";
for (int i = 0; i < str.length; i++) {
String newString1 = str[i].replaceAll(remove1, "");
String newString2 = newString1.replaceAll(remove2, "");
String newString3 = newString2.replaceAll(remove3, "");
String newString4 = newString3.replaceAll(remove4, "");
//fill in the table the names of the images
imageName[i] = (newString4);
//converts the name of each image to its ID
Integer keyImg = context.getResources().getIdentifier(imageName[i], "drawable", context.getPackageName());
imageNameInt[i] = keyImg;
/* try {
Class res = R.drawable.class;
Field field = res.getField(imageName[i]);
int drawableId = field.getInt(null);
imageNameInt[i]=drawableId;
} catch (Exception e) { Log.e("MyTag", "Failure to get drawable id.", e);}*/
}
return imageNameInt;
} |
dernièrement je fais appel à cette méthode
Code:
1 2 3 4 5
| Resources res = context.getResources();
bookImagesFromStringArray = res.getStringArray(R.array.bookImages);
Integer[] bookID = getImageId(bookImagesFromStringArray, context);
System.out.println("Image ID : " + Arrays.toString(bookID)); |
puis-je encore optimiser cette méthode ?
:roll:
Merci infiniment.