如何整齐地初始化多个TextViews?

时间:2014-07-03 09:12:08

标签: java android view textview initialization

我想让这段代码更简洁,但我想保留每个TextViews的引用/名称。

    airportCodeText1 = (TextView) findViewById(R.id.airportCode1);
    airportCodeText2 = (TextView) findViewById(R.id.airportCode2);
    airportText1 = (TextView) findViewById(R.id.airport1);
    airportText2 = (TextView) findViewById(R.id.airport2);
    departureTime = (TextView) findViewById(R.id.departureTime);
    arrivalTime = (TextView) findViewById(R.id.arrivalTime);
    flightNunberText = (TextView) findViewById(R.id.flightNoText);
    desk = (TextView) findViewById(R.id.desk);
    gate = (TextView) findViewById(R.id.gate);
    flightNumberTitle = (TextView) findViewById(R.id.flightNoTitle);
    deskTitle = (TextView) findViewById(R.id.deskTitle);
    gateTitle = (TextView) findViewById(R.id.gateTitle);

1 个答案:

答案 0 :(得分:2)

你应该只使用一种方法来声明你想要初始化的不同变量的R.id。所以你首先应该在主体中声明方法,然后使用该方法初始化每个findViewById部分

我很欣赏这一点,但如果这个解决方案不适合您的需求,那么还有其他方法,包括列表视图来完成相同的任务。

Public class yourclassname extends Activity implements OnClickListener {

Text View airportCodeText1, airportCodeText2, airporttext1, airporttext2, departureTime, arrivalTime, flightNumberText, desk, gate, flightNumberTitle, deskTitle, gateTitle;



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

 private void initializer() {
        airportCodeText1 = (TextView) findViewById(R.id.airportCode1);
        //Repeat for each TextView 
        //I didnt wanna do the whole code for you.

       }