我正在尝试编写一个从主菜单(gridview)开始的应用程序,然后根据用户单击的图标创建一个新活动。现在我试图只为其中一个图标显示一个空白屏幕,以确保我可以成功创建一个新活动。我的主要活动叫做HomeScreen,当我点击第一个图标时应该启动的新活动叫做CulpaActivity。我发布了HomeScreen,CulpaActivity和Manifest。
public class HomeScreen extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
Drawable background = this.getResources().getDrawable(R.drawable.bg);
gridview.setBackgroundDrawable(background);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(HomeScreen.this, "" + position, Toast.LENGTH_SHORT).show();
Intent cuAppIntent = null;
switch (position){
case 0:
cuAppIntent.setClass(HomeScreen.this, CulpaActivity.class);
}
}
});
}
}
public class CulpaActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setBackgroundDrawable(null);
}
}
这是Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="columbia.android"
android:versionCode="1"
android:versionName="1.0" >
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true" />
<application
android:debuggable="true"
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".HomeScreen" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CulpaActivity" >
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
答案 0 :(得分:3)
我认为这是你的问题:
Intent cuAppIntent = null;
您将cuAppIntent
定义为null
,但在没有首先初始化cuAppIntent.setClass()
的情况下直接访问cuAppIntent
。
switch (position){
case 0:
cuAppIntent.setClass(HomeScreen.this, CulpaActivity.class);
}
要解决此问题,请先尝试初始化:
Intent cuAppIntent = new Intent();
然后添加:
startActivity(cuAppIntent);
在致电cuAppIntent.setClass()
答案 1 :(得分:1)
cuAppIntent = new Intent();
cuAppIntent.setClass(HomeScreen.this, CulpaActivity.class);
startActivity(cuAppIntent);
创建意图后。此外,您可能正在生成空指针异常,因为您似乎没有调用生成意图。
答案 2 :(得分:0)
在您主页活动中的这部分代码中
Intent cuAppIntent = null;
switch (position){
case 0:
cuAppIntent=(homeScreen.this, CulpaActivity.class);
startActivity(cuAppIntent);
break;