创建水平滚动视图时出错?

时间:2011-09-19 08:42:24

标签: android

我在android工作,我想制作一个scrollview。 这是我的代码:

package com.pericent;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;

public class HelloTabWidget extends Activity  {

    private String TAG="HelloTabWidget";



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

        Log.v(TAG,"i am just before everything");
        HorizontalScrollView hr=new HorizontalScrollView(this);
        hr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
        LinearLayout layout=new LinearLayout(this);
        LinearLayout mainlayout=new LinearLayout(this);
        mainlayout=(LinearLayout)findViewById(R.id.upper1);
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        Log.v(TAG,"i am just after the declarations");
        for(int i=0;i<100;i++){
            TextView txt=new TextView(this);
            txt.setText("Text " + i );
            layout.addView(txt);
        }
        Log.v(TAG,"i am after the for loop");
        hr.addView(layout);

        mainlayout.addView(hr);//<<---this is creating NullPointerException
        setContentView(R.layout.cecking);
        Log.v(TAG,"i am after the everything");

  }
}

这是我的cecking.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/upper1">

</LinearLayout>

每当我运行程序时,都会发生此错误: -

Unable to start activity ComponentInfo{com.pericent/com.pericent.HelloTabWidget}: java.lang.NullPointerException

并在此行中发生错误: - mainlayout.addView(hr);

请帮我找出错误的原因。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

您没有为活动设置任何布局 以及你没有为该Activity充气check.xml。 这就是无法找到mainlayout并导致NullPointerException的原因 试试这种方式: checking.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" android:layout_height="fill_parent">
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/upper1">
        </LinearLayout>
</LinearLayout>

然后在onCreate()的{​​{1}}内设置您的布局 像这样:

Activity

答案 1 :(得分:0)

这可能是因为您尚未设置

.setLayoutParams(new Layout...

用于mainlayout,错误语句行对象。

相关问题