gpt4 book ai didi

android - 自定义 View 只显示一次

转载 作者:行者123 更新时间:2023-11-29 22:23:34 25 4
gpt4 key购买 nike

我做了一个非常简单的 customView,一个灰色矩形,矩形内有任意数量的红色标记,用百分比标记。

public class DemoView extends View {
private ShapeDrawable mDrawable;
private ArrayList<ShapeDrawable> mMarks;

public DemoView(Context context, int[] marks) {
super(context);
int x = 0;
int y = 0;
int width = 100;
int height = 10;
// Timeline Initially empty

mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setColor(Color.GRAY);
mDrawable.setBounds(x, y, x + width, y + height);
// Add marks
if (marks != null && marks.length % 2 == 0) {
mMarks = new ArrayList<ShapeDrawable>(marks.length / 2);
ShapeDrawable mark;
for (int i = 1; i < marks.length; i = i + 2) {
mark = new ShapeDrawable(new RectShape());
mark.getPaint().setColor(Color.RED);
mark.setBounds(x + marks[i - 1], y, x + marks[i], y + height);
mMarks.add(mark);
}
}
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mDrawable.draw(canvas);
if (mMarks != null)
for (ShapeDrawable mark : mMarks)
mark.draw(canvas);
}

但是我不知道如何使用 View 。每次我尝试在线性布局或相对布局中添加多个 View 时,我只会看到其中一个 View 。

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/llayout"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

布局代码:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout) findViewById(R.id.llayout);
demoview = new DemoView(this, new int[]{10,15,35,60});
demoview.setId(ID_NUM++);
ll.addView(demoview);
demoview2 = new DemoView(this, new int[]{0,1,3,6});
demoview2.setId(ID_NUM++);
ll.addView(demoview2);
demoview3 = new DemoView(this, new int[]{25,60});
demoview3.setId(ID_NUM++);
ll.addView(demoview3);
demoview4 = new DemoView(this, new int[]{15,60});
demoview4.setId(ID_NUM++);
ll.addView(demoview4);

}

结果:

Result of linearlayout code above..

这是错误的路线吗?我是否遗漏了多次使用此 View 的一些明显关键?如果这不是正确的路线,是否还有其他方法可以制作自定义形状?也许扩展 rectShape?

最佳答案

听从 Mibollma 的建议,我观看了上面的视频,这是来自 Google I/O 2009 的关于加速用户界面的视频。

该信息在两年后绝对仍然适用。通过使用 ViewHolder,我不仅能够加快所有 ListView 的速度,而且还能找到问题的答案。

创建自定义 View 时,必须重写两个方法,第一个在上面列出:onDraw。

缺少的方法? onMeasure()。可以找到更多信息here.

关于android - 自定义 View 只显示一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6552126/

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