Man*_*hot 5 android listview focus
我有一个包含自定义行的ListView.此自定义行具有以下UI元素
要求是每当列表行被选中时,将会有以下更改
imageView1背景,颜色改变了
imageView1颜色已更改
textview1的颜色,大小和字体是变化的
textview2颜色,大小改变了
textview3颜色,大小改变
为此设计最好的方法是什么?
AFAIK我们无法在选择器中应用样式.有没有更好的方法来处理这个而不是在java代码中处理?
我们有setOnItemSelectedListener,可以在Listview上设置,它将具有以下回调方法:
i)onItemSelected
ii)onNothingSelected
然而,没有回调方法提供失去焦点的项目的细节.这是一个更好的地方吗?
提前致谢.
我认为你想要在这里做的是创建一个复合控件。您可以在 SDK 目录的samples//ApiDemos 子目录中找到示例(如果没有这些目录,您可能需要下载Android 源代码)。
我要做的是创建一个类,该类继承您用于自定义行的任何类型的布局。假设LinearLayout这个例子是 a 。在子类构造函数中,您可以从资源中扩充布局,找到子视图并将它们附加到实例变量,然后将 LinearLayout 返回给调用者。
在这个子类中,您可以setSelected以任何您想要的方式覆盖和操作子视图。
这是我根据您的帖子描述的示例:
public class MyCustomLayout extends LinearLayout {
public ImageView imageView1; // These are public since you likely want
public ImageView imageView2; // to set them in your Adapter.
public TextView textView1;
public TextView textView2;
public TextView textView3;
public MyCustomLayout(Context ctxt) {
super(ctxt);
// The call below attaches the items in the mycustomlayout.xml file to this
// instance, which serves as the root element in the layout.
LayoutInflater.from(ctxt).inflate(R.layout.mycustomlayout, this, true);
imageView1 = (ImageView)findViewById(R.id.imageview1);
imageView2 = (ImageView)findViewById(R.id.imageview2);
textView1 = (TextView)findViewById(R.id.textview1);
textView2 = (TextView)findViewById(R.id.textview2);
textView3 = (TextView)findViewById(R.id.textview3);
}
@Override
public void setSelected(boolean selected) {
super.setChecked(selected);
if (selected) {
imageView1.setBackgroundColor(0xFFFF0000); // whatever color you want
// Do all the rest of the setting of your subviews here for
// the case when the row is selected.
} else {
imageView1.setBackgroundColor(0xFF000000); // whatever color you want
// Do all the rest of the setting of your subviews here for
// the case when the row is not selected
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在 mycustomlayout.xml 文件中,您想要使用该<merge>标记,这样就不会创建不需要的布局:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imageview1" />
<ImageView
android:id="@+id/imageview2" />
<TextView
android:id="@+id/textview1" />
<TextView
android:id="@+id/textview2" />
<TextView
android:id="@+id/textview3" />
</merge>
Run Code Online (Sandbox Code Playgroud)
显然,我已经省略了上面子视图的所有配置,但您应该了解如何设置 XML 文件。如果您不想欺骗 XML 和 LayoutInflater,您也可以在代码中执行此操作。您可以在 Android 开发博客上查看这篇有用的博客文章,其中讨论了类似的案例。
然后,在您的适配器中,getView您可以创建(或回收) 的实例MyCustomLayout,设置它们,并让框架负责跟踪哪些行被选择,哪些行未被选择。