我想在加載時將焦點設置在列表視圖上。我有一個要求,我想在列表視圖中實現導航,就像按下向上按鈕時我希望它向上移動一樣,向下按鈕也類似。到目前爲止,我已經嘗試了幾乎大部分的方法,如 set selection(position),listview.requestfocus(),list.setSelected(true),list.setItemsCanFocus(true),但目前爲止還沒有成功。 我也試過這個方法來獲取列表視圖中的視圖,它工作正常:如何將焦點設置在0列表視圖上
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
then I am getting the view and trying to set focus..however it does not work
runOnUiThread(new Runnable() {
public void run() {
getViewByPosition(0, list);
View v = getViewByPosition(0, list);
Log.v("WifiScanReceiver", "View found: " + v);
v.setFocusable(true);
v.setFocusableInTouchMode(true);
v.requestFocus();
}
});
任何建議,以實現重點將是appreciated.I已經研究了很多,迄今沒有奏效。
public class MainActivity extends Activity {
ListView listView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get ListView object from xml
listView = (ListView) findViewById(R.id.list);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.post(new Runnable() {
@Override
public void run() {
listView.setSelection(0);
}
});
我想你想要的是「setSelection」方法,而不是焦點,如果我正確理解你的問題。看看這個方法:http://developer.android.com/reference/android/widget/ListView.html#setSelection(int) – kha 2015-02-23 09:59:52
@kha:我試過這個,但它並沒有像我想要的任何區別該列表的第一個索引要默認聚焦..setselection在這種情況下不起作用 – 2015-02-23 10:06:10