2015-11-08 88 views
0

我的佈局包含一個LinearLayout,其中包含一個充氣時的單個按鈕。Android setNextFocusDown以編程方式創建的視圖

通脹後,3個觀點以編程方式添加,我希望能夠做的是設置初始按鈕,在我的循環創建的第一個視圖的nextFocusDown,像這樣的內容:

ImageButton btnBack = (ImageButton) this.findViewById(btnBack); 

forV(x=0;x<=45;x++) { 

    LayoutInflater inflater = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    LinearLayout l = (LinearLayout) inflater.inflate(R.layout.my_great_item, null); 

    // what I really want to be able to do here is something like 
    // if(x==0) btnBack.setNextFocusDown(l); 
    // but here there only exists the method setNextFocusDownId - I can't pass a view directly to the function. 

    l.setFocusable(true); 
    l.setClickable(true); 

    ... 

    l.setOnFocusChangeListener(new View.OnFocusChangeListener() { 
     ... 
    }); 

    l.setOnClickListener(new View.OnClickListener() { 
     ... 
    }); 

    mybaseview.addView(l) 
} 

的問題是,根據評論,似乎沒有方法setNextFocusDown(View) - 所以我不能找出一種方法來實現這一點,除了嵌套在一個虛擬的父佈局編程創建的視圖 - 但我想盡可能避免這種情況。

回答

0

創建一個文件values/ids.xml:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <item name="your_custom_id" type="id"/> 
</resources> 

不是改變這樣的代碼:

ImageButton btnBack = (ImageButton) this.findViewById(btnBack); 

for(x=0;x<=45;x++) { 
    LayoutInflater inflater = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    LinearLayout l = (LinearLayout) inflater.inflate(R.layout.my_great_item, null); 

    if (x==0) { 
     l.setId(R.id.your_custom_id); 
     btnBack.setNextFocusDown(R.id.your_custom_id); 
    } 

    l.setFocusable(true); 
    l.setClickable(true); 

    ... 

    l.setOnFocusChangeListener(new View.OnFocusChangeListener() { 
     ... 
    }); 

    l.setOnClickListener(new View.OnClickListener() { 
     ... 
    }); 

    mybaseview.addView(l) 
}