开发者

Get Id of Button in android

I have a Button Adapter, i make 9 buttons in a gridview, then i set id for each button. BUt how do i use a button in another class, example: i need to change background of button with id 5. Here's my 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(INTarraywithpi开发者_开发百科ctures[position]);  

     btn.setId(position);  //here i set Id

     return btn;  
    }  
   }  


After calling setContentView, you can use Button b = (Button)findViewById(theButtonId); to get a reference to it.


you can use setTag(value) and getTag(value) instead of setId()...

for more info..go setTag and getTag


if u want to access your button in another class just declare the button as final and static....and if u declare the button as public then u can access the button in another class by creating the object of the class which contains button.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜