Android:Inflater无法在自定义视图中工作。如何写文字视图?

时间:2017-02-06 12:29:15

标签: android android-custom-view android-inflate

我创建了一个自定义视图。这是我的自定义视图的布局。

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.lenze.android.poc_arcdraw.ArcView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"/>

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="172dp"
    android:id="@+id/textView"/>

</RelativeLayout>

上述文件的名称为sample_arc_view.xml。我的视图文件是

public class ArcView extends RelativeLayout {
    private TextView mTextView;
    public ArcView(Context context, AttributeSet attrs) {
        super(context, attrs);
        readParametersFromAttributeSet(context.obtainStyledAttributes(attrs, R.styleable.ArcView));
        init(context);
    }
       private void init(Context context) {

       View view = LayoutInflater.from(getContext()).inflate(R.layout.sample_arc_view,this); // stuck here
        mTextView = (TextView) view.findViewById(R.id.textView); // this line is never executed

    }
}

现在,每当我执行此代码时,它总会卡在inflater中。我无法进入下一行并编程崩溃。由于没有错误或异常,日志没有帮助。 Here是日志的链接。

我想在文本视图中编写一些动态文本。

2 个答案:

答案 0 :(得分:0)

你进入无限的膨胀递归。一旦你试图膨胀 sample_arc_view.xml,android inflater将调用ArcView的构造函数。 Wich将尝试在无休止的递归调用中扩充相同的布局。

答案 1 :(得分:0)

感谢您的回答。尼古拉的回答帮助我找到了错误。它确实是stackoverflow,但从未被抛出。我不知道为什么。我稍微修改了我的代码。 新XML就像

<RelativeLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"/>

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="172dp"
    android:id="@+id/textView"/>

我删除了行:com.lenze.android.poc_arcdraw.ArcView,因此删除了对ArcView构造函数的递归调用。 我还将充气机的代码修改为:

    LayoutInflater inflater= (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View mCustomView = inflater.inflate(R.layout.sample_arc_view, this,true);