昨天晚上本来是照着郭霖大大的《第一行代码》敲着示例代码的,写到listView的时候,自己突发奇想想要在listview下面加一个editview和一个Button
做成了这样
功能很简单,上面是listview,下面footerview,就是按send就能把edittext中的文本用toast形式发送出来。
但是!!
最开始直接
myButton = (Button)findViewById(R.id.button_1);
报错说myButton是空指针,程序模拟崩溃爆炸,此时我的main_activity.xml代码如下
<span style="font-size:14px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_partent" >
</ListView>
</LinearLayout></span>
foodView布局代码如下
<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="@+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send"/>
<EditText
android:id="@+id/edit_text"
android:layout_width = "match_parent"
android:layout_height="wrap_content"
android:hint="Here is what U Clicked"/>
</LinearLayout></span>
然后U大神告诉我,要把布局包含进去
我在main_activity.xml布局文件中的listView下面添加了一行代码就通过了
<include layout = "@layout/other"/>
但是!!
问题又来了
虽然添加了事件监听器,但是怎么点都没有反应
foodView布局加载代码
<span style="font-size:14px;"><span style="white-space:pre"> </span>LayoutInflater infla = LayoutInflater.from(MainActivity.this);
View footView = infla.inflate(R.layout.other, null);
myButton = (Button) findViewById(R.id.button_1);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,editText.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
editText = (EditText) findViewById(R.id.edit_text);
listView.addFooterView(footView, null, true);</span>
上网查了好久,终于在某个不起眼的角落旮旯里,看到了问题所在。
在myButton和editText这两个控件的findviewbyid方法前加上 footView. 即可。
最后终于成功了,截个图纪念一下 \(^o^)/YES!\(^o^)/YES!\(^o^)/YES!
PS:感谢U大神!!!