Obtenir l'Id du Bouton android
J'ai un Bouton de l'Adaptateur, je fais 9 boutons dans un gridview, puis j'ai mis l'id pour chaque bouton. Mais comment puis-je utiliser un bouton dans une autre classe, par exemple: j'ai besoin de changer d'arrière-plan du bouton avec l'id 5. Voici mon code
public class ButtonAdapter extends BaseAdapter {
static Button btn;
private Context mContext;
//Gets the context so it can be used later
public ButtonAdapter(Context c) {
mContext = c;
}
//Total number of things contained within the adapter
public int getCount() {
return somestringarray.length;
}
//Require for structure, not really used in my code.
public Object getItem(int position) {
return null;
}
//Require for structure, not really used in my code. Can
//be used to get the id of an item in the adapter for
//manual control.
public long getItemId(int position) {
return position;
}
public View getView(int position,
View convertView, ViewGroup parent) {
if (convertView == null) {
//if it's not recycled, initialize some attributes
btn = new Button(mContext);
btn.setLayoutParams(new GridView.LayoutParams(85, 85));
btn.setPadding(8, 8, 8, 8);
btn.setOnClickListener(new MyOnClickListener(position));
}
else {
btn = (Button) convertView;
}
btn.setText(somestringarray[position]);
//filenames is an array of strings
btn.setTextColor(Color.BLACK);
btn.setBackgroundResource(INTarraywithpictures[position]);
btn.setId(position); //here i set Id
return btn;
}
}
- Ne
Button btn5 = (Button) findViewById(5)
pas de travail? - J'ai besoin d'utiliser le bouton dans une autre classe (mais dans le même package) et je ne sais pas vraiment comment faire pour obtenir ce travail.
Vous devez vous connecter pour publier un commentaire.
Après l'appel de
setContentView
, vous pouvez utiliserButton b = (Button)findViewById(theButtonId);
pour obtenir une référence à elle.vous pouvez utiliser setTag(valeur) et getTag(valeur) au lieu de setId()...
pour plus d'info..aller setTag et getTag
si tu veux accéder à votre bouton dans une autre classe, il suffit de déclarer la touche finale et statique....et si u déclarer le bouton en tant que public, alors u peut accéder au bouton dans une autre classe, par la création de l'objet de la classe qui contient le bouton.