如何从XML中扩展LinearLayout

yet*_*ner 5 android android-custom-view android-layout android-linearlayout

任何人都可以建议一种方法来改进这个API8的例子吗?虽然他们说这些视图可以用XML定义,但他们实际上做的是用java编写代码.我明白为什么他们想要.他们已经将一些成员添加到扩展的LinearLayout中,并且这些值是在运行时确定的.

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

来自API8示例,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);
        ...
Run Code Online (Sandbox Code Playgroud)

我想因为LinearLayout有一个android:id ="@ + id/LinearLayout01",我应该能够在OnCreate中做到这一点

SpeechView sv = (SpeechView) findViewById(R.id.LinearLayout01);
Run Code Online (Sandbox Code Playgroud)

但它永远不会击中我添加的最小构造函数:

    public class SpeechView extends LinearLayout {
       public SpeechView(Context context) {
          super(context);
          System.out.println("Instantiated SpeechView(Context context)");
       }
       ...
Run Code Online (Sandbox Code Playgroud)

Kev*_*rth 11

我只是碰到了这个确切的问题我自己.我认为你(我们)需要的是这个,但我仍然在处理一些错误,所以我还不能肯定地说:

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

如果你有运气的话我会很想听.

编辑:现在就像这样为我工作.


yet*_*ner 3

看起来您夸大了位于文件 main_row.xml 中的布局。正确的?我的需求不同。我想膨胀 main.xml 中布局的 TextView 子级。

尽管如此,我还是使用了类似的解决方案。因为我已经在 onCreate 中从 XML 扩充了 LinearLayout

setContentView(R.layout.main);
Run Code Online (Sandbox Code Playgroud)

剩下的就是在我的 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);
Run Code Online (Sandbox Code Playgroud)

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

<TextView android:id="@+id/roleHeading" ... />
Run Code Online (Sandbox Code Playgroud)

为了提高效率,我能够将 LayoutInflater 移至 Activity 成员,以便它仅实例化一次。