【问题标题】:linking my java layout object with xml layout in android将我的java布局对象与android中的xml布局链接起来
【发布时间】:2014-02-23 06:55:15
【问题描述】:

我在我的 .java 文件中创建了一个 LinearLayout 对象,并尝试使用以下代码将它与我的 .xml layout 连接,但它没有响应。您能否向我解释一下为什么以及这段代码中有哪些错误?我已将 .xml 文件的 LinearLayoutid 命名为“root”。

public class MainActivity extends Activity {

    LinearLayout l;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView HelloWorldImageView = new ImageView(this);
        TextView t=new TextView(this);
        t.setText("hello");
        HelloWorldImageView.setImageResource(R.drawable.ic_launcher);
        l=new LinearLayout(this);
        l=(LinearLayout)findViewById(R.id.root);
        l.addView(t);
        l.addView(HelloWorldImageView);
        setContentView(l);
    }
}

【问题讨论】:

  • 您遇到了什么问题?你为什么要初始化l 两次?另外,你为什么不把这些Views 放在你的xml 中呢?然后你不必用new初始化它们。

标签: android


【解决方案1】:

这样做-

        setContentView(R.layout.yourxml);
        ImageView HelloWorldImageView = new ImageView(this);
        TextView t=new TextView(this);
        t.setText("hello");
        HelloWorldImageView.setImageResource(R.drawable.ic_launcher);
        l=(LinearLayout)findViewById(R.id.root);
        l.addView(t);
        l.addView(HelloWorldImageView);

您必须在其中包含根线性布局的 setContentView() 中设置该 xml 文件。

【讨论】:

  • 实际上我正在尝试不同的方法,这就是为什么这样做。问题是它停止工作,但现在,解决了,我明白了。谢谢大家。
【解决方案2】:

首先,您不需要 new LinearLayout 行。 findViewById() 将返回一个实例化版本。其他新的Views 也是如此。

其次,您想在拨打任何电话 findViewById() 之前先拨打 setContentView()。这样你设置layout(通过传递一个layoutid),Android 将在你的layout 中实例化所有Views,你可以通过findViewById() 获取对它们的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 2014-06-05
    • 2021-12-23
    • 2015-07-26
    • 2018-07-05
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多