在android中获取Button的Id

时间:2011-05-25 07:55:26

标签: java android background adapter

我有一个Button Adapter,我在gridview中制作9个按钮,然后我为每个按钮设置id。如何在另一个类中使用按钮,例如:我需要更改id为5的按钮背景。这是我的代码

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;  
    }  
   }  

3 个答案:

答案 0 :(得分:2)

致电setContentView后,您可以使用Button b = (Button)findViewById(theButtonId);来获取对它的引用。

答案 1 :(得分:0)

你可以使用setTag(value)和getTag(value)代替setId()......

了解更多信息..来自setTaggetTag

答案 2 :(得分:0)

如果你想在另一个类中访问你的按钮,只需将按钮声明为final和static ....如果你将按钮声明为public,那么你可以通过创建类的对象来访问另一个类中的按钮。包含按钮。