Reusing layout XML and the code behind

后端 未结 2 486
无人及你
无人及你 2020-12-09 10:50

I am trying to turn a couple buttons into a reusable component in Android. I have successfully gotten the XML / UI portion working, but I can\'t figure out how to make code

2条回答
  •  一生所求
    2020-12-09 11:24

    What I do is make an actual component that contains all of the common code and use it directly. Here is a dumbed down version of the component class:

    public class NavigationBar extends LinearLayout {
        public NavigationBar(Context context) {
            super(context);
            setupView(context);
            hookupButtons(context);
        }
        public NavigationBar(Context context, AttributeSet attrs) {
            super(context, attrs);
            setupView(context);
            hookupButtons(context);
        }
        private void setupView(Context context) {
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // inflate whatever layout xml has your common xml
            inflater.inflate(R.layout.navigation_bar, this);
        }
    }
    

    In my class hookupButtons does exactly what you think it would do. :-)

    Then my in all my layout xmls look similar to this:

    
    
        
        
    
    

    In the onCreate of each activity I also have this (that you can adapt to whatever you need):

    NavigationBar navbar = (NavigationBar) findViewById(R.id.nav_bar);
    navbar.setText("Playlists");
    

    Of course you will need to add whatever imports you need.

    EDIT

    Just a clarification: My navigation_bar.xml looks very similar to yours except I don't have the merge lines in mine.

    EDIT 2

    Here is what hookupButtons looks like. I'm only showing one button but you should get the idea.

    private void hookupButtons(final Context context) {
        ImageButton playlistsBtn = (ImageButton)findViewById(R.id.nav_playlists_btn);
        if (context instanceof PlaylistsActivity) {
            playlistsBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.nav_playlists_active));
        } else {
            playlistsBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(context, PlaylistsActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    context.startActivity(i);
                }
            });
        }
    }
    

提交回复
热议问题