use of multiple tags in layout with ButterKnife

前端 未结 2 1442
后悔当初
后悔当初 2021-01-12 04:30

I have a layout where I include the same sub-layout multiple times, each one with a different role:



        
2条回答
  •  醉话见心
    2021-01-12 04:47

    The idea of my answer is the same as Budius proposed, I found it in a related issue on ButterKnife's github repo. Original Author is TomazMartins

    The MainActivity:

    public MainActivity extends AppCompatActivity {
        // 1. First, we declare the layout that was included as a View objects.
        @BindView(R.id.layout_1) View layout_1;
        @BindView(R.id.layout_2) View layout_2;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // 2. In here, we bind the included layouts
            ButterKnife.bind(this);
    
            // 4. Then, we create objects of the type of the IncludedLayout.
            //      In this example the layout reuse the same layout twice, so, there are two
            //      IncludedLayouts.
            IncludedLayout includedLayout_1 = new IncludedLayout();
            IncludedLayout includedLayout_2 = new IncludedLayout();
    
            // 5. We bind the elements of the included layouts.
            ButerKnife.bind(includedLayout_1, layout_1);
            ButerKnife.bind(includedLayout_2, layout_2);
    
            // 6. And, finally, we use them.
            includedLayout_1.displayed_text.setText("Hello");
            includedLayout_2.displayed_text.setText("Hey!");
        }
    
        // 3. We create a static class that will be an container of the elements
        //     of the included layout. In here we declare the components that
        //     hold this. In this example, there is only one TextView.
        static class IncludedLayout {
            @BindView(R.id.displayed_text) TextView displayed_text;
        }
    }
    

    The XML of the MainAcitvity:

    
    
    
            
            
    
    
    

    The XML of the Included Layout:

    
    
        
    
    

    That's it!

    When i ran it, although the id was the same, because I reused it, the text in the TextView was different.

提交回复
热议问题