如何在我的布局中膨胀 textview xml?

Rah*_*pta 5 android android-layout

我创建了一个自定义的 textview 类,我试图在我的主 xml 中对其进行扩充。这是我的代码:-

public class CustomTextView extends TextView{

public CustomTextView(Context context) {
    super(context);
    LayoutInflater li = LayoutInflater.from(context);
    TextView view = (TextView) li.inflate(R.layout.customtextview,null);
    view.setBackgroundColor(Color.RED);
}
Run Code Online (Sandbox Code Playgroud)

}

自定义文本视图.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:text="sgfiughbjkh"
    android:id="@+id/customtext"
    android:layout_height="match_parent" >

</TextView>
Run Code Online (Sandbox Code Playgroud)

在我的主要活动 xml 中,我只有一个线性布局:-

    LinearLayout main = (LinearLayout)findViewById(R.id.mainView);
    CustomTextView cus = new CustomTextView(this);
    main.addView(cus);
Run Code Online (Sandbox Code Playgroud)

我知道如果我将它扩展到线性布局而不是 textview 并添加一个 lienarlayout 作为父级,并且在它的 textview 中,它可以工作。

但问题是我想只用一个 textview 来膨胀一个 xml 并膨胀它,上面的代码不起作用。请建议

如何使用布局充气器对仅包含一个文本视图的 xml 进行充气?

Min*_*wzy 5

// inflate text view
    TextView textView =  (TextView) getLayoutInflater().inflate(R.layout.customtextview, null);

// add it to your view
// in your condition, we will add it to Linear Layout
  LinearLayout main = (LinearLayout)findViewById(R.id.mainView);
  main.addView(textView);
Run Code Online (Sandbox Code Playgroud)


小智 1

您可以在 Eclipse 图形界面的“自定义和库视图”标题下找到所有自定义创建的视图。

如果您的 CustomTextView 位于包“com.example”中,那么您可以将自定义组件定义为:

<com.example.CustomTextView
    android:id="@+id/customTextView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
Run Code Online (Sandbox Code Playgroud)