【问题标题】:How to Inflate Extended LinearLayout from XML如何从 XML 膨胀扩展的线性布局
【发布时间】:2011-01-03 22:19:44
【问题描述】:

谁能提出改进这个 API8 示例的方法?虽然他们说视图可以在 XML 中定义,但实际上他们所做的是用 java 编写它们。我明白他们为什么要这样做。他们在扩展的 LinearLayout 中添加了一些成员,并且值是在运行时确定的。

根据哦,宇宙中的每个人,布局指令应该移动到XML。但是对于这个应用程序,在运行时逻辑中保持原样设置文本是有意义的。所以我们有一个混合方法。膨胀视图,然后填充动态文本。我很难弄清楚如何完成它。这是来源和我尝试过的内容。

来自API8 Examples, List4.java

  private class SpeechView extends LinearLayout {
     public SpeechView(Context context, String title, String words) {
        super(context);

        this.setOrientation(VERTICAL);

        // Here we build the child views in code. They could also have
        // been specified in an XML file.

        mTitle = new TextView(context);
        mTitle.setText(title);
        ...

我想既然 LinearLayout 有一个 android:id="@+id/LinearLayout01",我应该可以在 OnCreate 中做到这一点

SpeechView sv = (SpeechView) findViewById(R.id.LinearLayout01);

但它从未达到我添加的最小构造函数:

    public class SpeechView extends LinearLayout {
       public SpeechView(Context context) {
          super(context);
          System.out.println("Instantiated SpeechView(Context context)");
       }
       ...

【问题讨论】:

    标签: android android-layout android-linearlayout android-custom-view


    【解决方案1】:

    我自己也遇到了这个exact问题。我认为你(我们)需要的是这个,但我仍在解决一些错误,所以我还不能肯定地说:

    public class SpeechView extends LinearLayout {
            public SpeechView(Context context) {
               super(context);
               View.inflate(context, R.layout.main_row, this);
            }
            ...
    

    我很想知道你是否有运气。

    编辑:它现在对我来说就像这样工作。

    【讨论】:

      【解决方案2】:

      看起来您膨胀了位于文件 main_row.xml 中的布局。正确的?我的需求不一样。我想膨胀我在 main.xml 中的 Layout 的 TextView 子项。

      不过,我使用了类似的解决方案。由于我已经在 onCreate 中从 XML 中对 LinearLayout 进行了膨胀

      setContentView(R.layout.main);
      

      剩下的就是在我的 View 构造函数中从 XML 膨胀 TextView。以下是我的做法。

      LayoutInflater li = LayoutInflater.from(context);
      LinearLayout ll = (LinearLayout) li.inflate(R.layout.main, this);
      TextView mTitle = (TextView) ll.findViewById(R.id.roleHeading);
      

      R.id.roleHeading 是我正在膨胀的 TextView 的 id。

      <TextView android:id="@+id/roleHeading" ... />
      

      为了提高效率,我可以将 LayoutInflater 移动到一个 Activity 成员中,这样它只会被实例化一次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多