创建一个android自定义视图,而不是使用不同数据的多个视图

时间:2018-11-28 10:55:45

标签: android android-layout

我在Java类中创建了5个不同的视图。它们由构造函数,一个由所有构造函数调用的init方法和一个绘制图形的onDraw方法组成。

在每个视图中,由于图形不同,因此init方法和onDraw会加载不同的数据。但是init和onDraw基本相同。

我可以创建一个可以重用的自定义视图吗?

在视图中,每个视图都有一个textview。 textview也非常相似,除了将数据加载到其java类中之外,还可以创建一个自定义 自定义视图使用的textview?我看到的所有示例都使用自定义textview,加载数据的方式没有任何区别,我必须确定正在调用哪个视图, 以便加载正确的数据。

这里是布局的示例(包括一个2个视图以简化布局,还从不必要的布局特定内容中清除了该视图):

<TableRow
    android:layout_width="match_parent" >
    <com.company.views.FirstView
        android:id="@+id/firstView"
        android:layout_height="match_parent" />
    <com.company.views.FirstTextView
        android:id="@+id/firstTextView"
        android:layout_height="match_parent"/>
</TableRow>
<TableRow
    android:layout_width="match_parent" >
    <com.company.views.SecondView
        android:id="@+id/secondView"
        android:layout_height="match_parent" />
    <com.company.views.SecondTextView
        android:id="@+id/secondTextView"
        android:layout_height="match_parent"/>
</TableRow>

以下是其中一种视图的示例(也已删除):

public class FirstView extends View {
  Paint paint;
  int y = 0;

  public FirstView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
  }

  private void init(Context context, AttributeSet attrs) {
        paint = com.company.helpers.Drawing.LineStyle("#00FF00", screenResolution.lineThickness); // <- the color is one of the differences for each view
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    y=GraphType.SpecificGraphType; // <- this is one of the other differences for each view

    // drawing part is irrelevant

    invalidate();
  }
}

以下是其中一种文本视图的示例:

public class FirstTextView extends AppCompatTextView {
    private string defaultText;

    public FirstTextView(Context context) {
        super(context);
        init(null, 0);
    }

    public FirstTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public FirstTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {
        textView = (TextView)findViewById(R.id.firstTextView);
        defaultText=Model.getInstance().SpecificGraphType; // <- this is one of the differences for each textview
    }
}

2 个答案:

答案 0 :(得分:1)

发现它应有的功能,但在覆盖setText()时出现了一个minnor代码错误。因此,如果有人想分享一个视图,您可以看一下我上面的示例。

答案 1 :(得分:1)

由于自定义视图扩展了TextView,因此无需执行findViewById。您的对象本身已经是视图。

因此,您只需在init()中调用setText(“ even awesomer”);

您的代码中断了,因为findViewById返回null,然后您得到一个NPE尝试在其上调用setText()。

要在视图中区分视图,只需使用getId()。

private void init(AttributeSet attrs, int defStyle) {
if (getId() == R.id.firstTextView) {
    ...
} else if (getId() == R.id.secondTextView) {
    ...
}
...
}