编写一个扩展ListActivity的应用程序Menu.java,我在列表活动上方的顶部添加了一个TextView标头。
标题和列表活动的布局正是我想要的,但当我点击说第1项时,吐司会弹出并说“第2项”已选中。当我点击第2项时…“第3项”已选定。但当我点击Item3时,应用程序崩溃并显示了一堆运行时错误。
在我实现头之前,它没有这样做。我搜索了又搜索stackoverflow和android开发网站,似乎找不到答案。
我已经将标题设置为false,因此无法点击。
提前感谢!很抱歉,我错过了一些显而易见的东西。。。这里的新手。:P
//this is Menu.java
package com.example.mytexts;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Menu extends ListActivity {
String[] values = new String[] { "Item1", "Item2", "Item3" };
public void onCreate(Bundle biscuits) {
super.onCreate(biscuits);
setContentView(R.layout.text_layout);
ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.header,
(ViewGroup) findViewById(R.id.header__root));
lv.addHeaderView(header, null, false);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String cheese = (String) getListAdapter().getItem(position);
Toast.makeText(this, cheese + " selected", Toast.LENGTH_SHORT).show();
try {
Class ourClass = Class.forName("com.example.addsubtract." + cheese);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
//this is header.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/header__root"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/black"
android:orientation="vertical" >
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/darkblue"
android:gravity="center"
android:padding="10dp"
android:text="Messages"
android:textSize="20dp" >
</TextView>
</LinearLayout>
//this is text_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="none" >
</ListView>
<TextView
android:id="@+id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nothing to Display" >
</TextView>
</LinearLayout>