gpt4 book ai didi

android - 如何将焦点设置为 0 索引的 ListView

转载 作者:太空狗 更新时间:2023-10-29 16:15:37 25 4
gpt4 key购买 nike

我试图在加载 ListView 时将焦点设置在 ListView 上。我有一个要求,我想在 ListView 上实现导航,就像按下向上按钮时我希望它向上移动一步,类似于向下按钮。到目前为止,我已经尝试了几乎大多数方法,例如set selection(position),listview.requestfocus(), list.setSelected(true),list.setItemsCanFocus(true) 但到目前为止没有任何效果。我也试过这种方法来获取 ListView 中的 View 并且它工作正常:

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();


}
});

任何实现焦点的建议将不胜感激。我已经研究了很多,但到目前为止没有任何效果。

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

最佳答案

大家好,非常感谢你们的精彩回复,他们都非常有帮助。然而,真正起作用的是:

list.post(new Runnable() {

@Override
public void run() {
list.getChildAt(indexPos + 1).setBackgroundColor(
Color.RED);
list.getChildAt(indexPos).setBackgroundColor(
Color.BLACK);
// String selectedFromList = (String) (list
// .getItemAtPosition(0));
Log.v("Case2", "Selected text is:" + selectedFromList);
}

我将列表背景设置为红色,对于选定的索引,我将背景更改为黑色。

关于android - 如何将焦点设置为 0 索引的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28670950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com