How to set text to multiple textview using ButterKnife library

1.9k views Asked by At

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 ");
    }
}
3

There are 3 answers

0
ashkhn On BEST ANSWER

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);
0
Shanmugavel GK On

Try this one.

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

    String names[] = {"aaa", "bbb", "ccc" ...};

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

        for (int i = 0; i < listTextView.size(); i++) {
            listTextView.get(i).setText(names[i]);
        }        
    }
0
Alex Shutov On

Android studio now has support for databinding out of the box. It is a mvvm pattern and official replacement for Butterknife, you may want to use it instead: https://developer.android.com/topic/libraries/data-binding/index.html