2011-09-19 26 views
0

我在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);

请帮我找出错误的原因。 预先感谢您。

回答

1

您没有为活动 设置任何布局,也没有为该活动的Inflate checking.xml设置布局。 这就是为什么mainlayout不能被发现并引起NullPointerException 试试这个方法: checking.xml

​​

,然后设置里面的Activity 这样的onCreate()布局:

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     this.setContenView(R.layout.checking); 
     mainlayout=(LinearLayout)findViewById(R.id.upper1); 
} 
+0

谢谢先生......我已经完成了这项工作,其实我已经犯了错误,我没有写下这行:-this.setContenView(R.layout.checking);再次感谢你... –

+0

Adil先生,您来自巴基斯坦的拉合尔......很高兴认识您..我来自印度...... –

0

这可能是因为你没有设置

.setLayoutParams(new Layout... 

为mainlayout,错误语句行对象。

+0

不,先生,这是不是因为在xml中我已经为这个mainlayout声明了这些属性。 –

+0

谢谢迈克盖茨,使用短键就是这样的诅咒。 :( –