addView导致我的Android应用程序崩溃

时间:2014-07-23 08:33:43

标签: android android-layout

我已经搜索了类似的帖子,但我无法找到解决问题的方法。 这是我的主要活动:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_mt);
        ScrollView sv = new ScrollView(this);
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        sv.addView(ll);
        RelativeLayout layout = (RelativeLayout)findViewById(R.layout.activity_mt);
        //layout.addView(ll);
        layout.addView(sv);
        setContentView(layout); 

我还将id添加到我的xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/activity_mt"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MtActivity" >

但每当我尝试运行我的应用程序时,它都会崩溃。问题出在哪儿?

2 个答案:

答案 0 :(得分:3)

更改

  RelativeLayout layout = (RelativeLayout)findViewById(R.layout.activity_mt)

RelativeLayout layout = (RelativeLayout)findViewById(R.id.activity_mt)

findViewById会在[{1}}中查找值,而不是R.id

答案 1 :(得分:2)

您对R.id.activity_mtR.layout.activity_mt感到困惑,因为您将它们命名为相同。只需替换

RelativeLayout layout = (RelativeLayout)findViewById(R.layout.activity_mt)

RelativeLayout layout = (RelativeLayout)findViewById(R.id.activity_mt)

以前,它会在null中存储layout,这就是为什么要投掷nullpointerexception。但在这样做之后,一切都会很酷。