2017-10-05 81 views
1

我想通过使用for循环与TextView对象a,b,c,d,e作为数组的元素来最小化代码。用于findViewById和setOnClickListener实现。任何对此特定编码的可操作演练都非常感谢!^ __^如何在for循环中实现一个TextView对象数组?

  • 以下是我通常如何执行TextView的方法。但我很厌烦写这么多行不必要的。

    TextView a,b,c,d,e;

    a=(TextView)findViewById(R.id.A); 
        b=(TextView)findViewById(R.id.B); 
        c=(TextView)findViewById(R.id.C); 
        d=(TextView)findViewById(R.id.D); 
        e=(TextView)findViewById(R.id.E); 
    
        a.setOnClickListener(this); 
        b.setOnClickListener(this); 
        c.setOnClickListener(this); 
        d.setOnClickListener(this); 
        e.setOnClickListener(this); 
    
  • 我的问题是,如果我可以用一个循环来设置所有已初始化 TextView的对象调用setOnClickListener()没有任何麻烦的 如下图所示:

    TextView a,b,c,d,e; 
    
    a=(TextView)findViewById(R.id.A); 
    b=(TextView)findViewById(R.id.B); 
    c=(TextView)findViewById(R.id.C); 
    d=(TextView)findViewById(R.id.D); 
    e=(TextView)findViewById(R.id.E); 
    

    的TextView [] textViews = {a,b,c,d,e};

    for (int count = 0; count < textViews.length; count++) { 
        textViews[count].setOnClickListener(this); 
    } 
    

**

  • 所有我想知道的是如何初始化对象TextView的一个 ,B,C,d,E以同样的方式,我拿给setOnClickListener为他们?事情是这样的,

    TextView[] textViews = {a, b, c, d, e}; 
    
    int[] textViewIds = {R.id.a, R.id.b, R.id.c, R.id.d, R.id.e}; 
    
    for (int count = 0; count < textViews.length; count++) { 
        textViews[count] = (TextView)findViewById(textViewIds[count]); 
    } 
    

**

+3

把ID放到列表/数组中并循环播放它们? –

+0

是。我会同意@bub – MetaSnarf

回答

1

//声明一个类的开始视图对象作为全局变量

View v_home, v_earning, v_rating, v_account; 

//创建视图和int数组用于查看视图阵列标识

View[] views ={v_home, v_earning, v_rating, v_account}; 
int[] viewsID ={R.id.v_home, R.id.v_earning, R.id.v_rating, R.id.v_account}; 

//然后findViewById和setOnClickListener在for循环

for (int v=0;v<views.length;v++){ 
     views[v] = findViewById(viewsID[v]); 
     views[v].setOnClickListener(this); 
    } 
3

这是我会怎么写呢(我没有在这里编译失误很抱歉)

ArrayList<TextView> textViews = new ArrayList<TextView>(); 

int[] tvIds = {R.id.A,R.id.B,R.id.C,R.id.D,R.id.E}; 

for(int index= 0; index<tvIds.length/* or .count forgot sorry*/; index++){ 

TextView tv = (TextView)findViewById(tvIds[index])); 
tv.setOnClickListener(this); 

textViews.add(tv); 

} 

或者你可以使用@Hank Moody回答,butterknife非常简单。

2

我使用ButterKnife进行视图绑定,并且它有很好的方法来做你想做的事情。

首先,你可以绑定视图列表

@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) 
List<TextView> nameViews; 

那么你可以申请不同势操作这份名单与“行动”,像这样:

static final ButterKnife.Action<View> SET_CLICK = new ButterKnife.Action<View>() { 
@Override 
public void apply(View view, int index) { 
    view.setOnClickListener(....listener); 
    } 
}; 

,然后应用这个动作

ButterKnife.apply(nameViews, DISABLE); 

查看示例here

UPD:如果您使用的科特林,看到Kotter Knife