Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

android - Using ListView : How to add a header view?

I looke at the ListView API and I saw the method:

addHeaderView(View v)

What I want to do is to have a layout above the list, is this possible ?

I tried doing something like :

  EditText et=new EditText(this);
  et.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT,     LayoutParams.WRAP_CONTENT));
  et.setInputType(InputType.TYPE_CLASS_TEXT); 
  addHeaderView(et); //makes app crash

I also tried

setContentView(R.layout.tryview);

but it also make the app crash.

Help is very much appreciated!

Edit : The code for this class is:

public class GroupsActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  String your_array_contents[] = {"a","ab","c"};
  setListAdapter(new ArrayAdapter<String>(this, R.layout.groups_layout, your_array_contents));
  EditText et=new EditText(this);
  et.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
  et.setInputType(InputType.TYPE_CLASS_TEXT); 

  ListView lv = getListView();
  lv.setTextFilterEnabled(true);
  lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

  lv.setAdapter(new ArrayAdapter<String>(GroupsActivity.this,
    android.R.layout.simple_list_item_multiple_choice, your_array_contents));
    lv.addHeaderView(et); //makes app crash
  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
      // When clicked, show a toast with the TextView text
     // Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
          //Toast.LENGTH_SHORT).show();
    }
  });
}


}
question from:https://stackoverflow.com/questions/7978359/using-listview-how-to-add-a-header-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add as many headers as you like by calling addHeaderView() multiple times. You have to do it before setting the adapter to the list view.

And yes you can add header something like this way:

LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...