Search code examples
androidbutterknife

How to set text to multiple textview using ButterKnife library


I have more than one textview and I want to add text to textview dynamically using Butter knife library. I have done this thing from my side in my code but I want to know any other good way to do same thing.

    public class MainActivity extends AppCompatActivity {

    @BindViews({ R.id.tv1, R.id.tv2})
    List<TextView> listTextView;  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // must define this otherwise null pointer error show.
        ButterKnife.bind(MainActivity.this);

        listTextView.get(0).setText("First TextView ");
        listTextView.get(1).setText("Second TextView ");
    }
}

Solution

  • You can store the text content in another array say textTitles and then use Butterknife's Action interface to set the text of each of the text view

    static final ButterKnife.Action<TextView> SET_TEXT = new ButterKnife.Action<TextView>() {
       @Override 
       public void apply(TextView view, int index) {
           view.setText(textTitles[index]);
       }
    };
    

    and then finally call

    ButterKnife.apply(listTextView, SET_TEXT);