开发者

noob: android button

开发者 https://www.devze.com 2023-04-09 21:31 出处:网络
I have two button b1 and b2 .If button b1 is pressed then perform a query q1 else if button b2 is pressed then perform an another query q2.

I have two button b1 and b2 .If button b1 is pressed then perform a query q1 else if button b2 is pressed then perform an another query q2.

if(b1_click)
{
  mCursor=//query
}
else if(b2_click)
{
  mCursor=//query
}

Please tell me ho开发者_开发问答w can i implement this.How to implement b1_click method or any inbuilt method which tell that button is pressed.I tried

Cursor c;
c=//querys

    if(b1.isPressed())
    {
        next.setOnClickListener
        (
            new View.OnClickListener()
            {
                @Override public void onClick(View v) {
                    c=db.getData1(); (getData1 method return cursor)
                }
            }
        );
    } 
   tv.append(c.getString(column_number) (tv=TextView)

   "Same as above for b2"

It is saying that cursor (c) should be final Help?


First of all I would recommend going through some tutorials Hello Android and you could also follow the code and samples in Common Tasks and How to do them in Android.

If you would read this carefully you would know that is very simple, something like this:

public class MyActiviy extends Activity implements OnClickListener{

     protected void onCreate(Bundle savedInstance){
          super.onCreate(savedInstance);
          setContentView(R.layout.myLayout);
          findViewById(R.id.Button1).setOnClickListener(this);
          findViewById(R.id.Button2).setOnClickListener(this);
          //more code...
     }

     public void onClick(View v){
          switch(v.getId()){
              case R.id.Button1:
                  //Button1 pressedd...do stuff
                  break;
              case R.id.Button2:
                  //Button2 pressed...do some other stuff
                  break;
              default:
                  break;
          }
     }
}


Try creating your OnClickListeners as private classes:

private class Button1ClickedListener implements OnClickListener {
  public void onClick( View v ) {
    //Do what needs to be done when button 1 is clicked.
  }
}

private class Button2ClickedListener implements OnClickListener {
  public void onClick( View v ) {
    //Do what needs to be done when button 2 is clicked.
  }
}

Then you set the onClick-listeners:

b1.setOnClickListener( new Button1ClickedListener() );
b2.setOnClickListener( new Button1ClickedListener() );

If you need the OnClickListeners to be able to use the cursor, you just need to declare it as a private field in the parent class of the OnClickListeners.

0

精彩评论

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

关注公众号