Android: Using <include/> to clone layouts, while using the same onClick button functions

StackOverflow https://stackoverflow.com/questions/13654077

  •  03-12-2021
  •  | 
  •  

質問

I want to use an "actionbar", like tapatalk has. Ofcourse I don't want to copy all button functions over and over again.

Is there a quick solution to do this?

Also, if I set the background drawable, I want it to be the same in the different layouts.

役に立ちましたか?

解決

I can see two approaches:

  • As I said in the comment, make all your activities extend a base activity of yours that implements the onClick. Mayebe I don't like this approach because it forces you to extend your base activity and if you want a listactivity in the future you may have some problems.

or (which I think it's much better)

  • simply have an helper class that accepts the activity as a constructor argument which will set the onclicks for you. You'll have to remember to instantiate that class (or call a static method if you are worried about creating objects), and that will do the job for you.

    public class OnClickHelper implements View.OnClickListener {
       Activity mActivity;
       public OnClickHelper(Activity a){
           mActivity = a;
       }   
    
    
       public setClickListeners(){
           Button b = (Button) mActivity.findViewById(R.id.Button1);
           b.setOnClickListener(this);
       }
    
       @Override
       public void onClick(View view) {
          switch(view.getId()){
             case R.id.button1:
    
             break;
          }
       }
    

    }

Regarding the background, go for styles. Have all the activities you want to have the same background using the same style (you can define it in the manifest).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top