Search code examples
androidandroid-layoutsetcontentview

How to use setContentView() in Android


I have a listview with footer in an activity.

What I want to do is:

  1. Make a listview.
  2. Add textviews to listview's footer
  3. Apply footer to listview.

Below is activity's onCreate method

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lecture_refer_room);

    // making listview...
    ListView listView = (ListView) findViewById(R.id.referList);
    ...
    ...
    String[] from = {"line1", "line2"};
    int[] to = {android.R.id.text1, android.R.id.text2};
    SimpleAdapter adapter = new SimpleAdapter(this, mapList,
              android.R.layout.simple_list_item_2, from, to);

           // footer_layout is in refer_footer.xml
     View footer = getLayoutInflater().inflate(R.layout.refer_footer, null, false);
    LinearLayout ll = (LinearLayout)findViewById(R.id.footer_layout);

    TextView tv= new TextView(this);
    tv.setText(element.text());
    tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
    tv.setVisibility(View.VISIBLE);
    ll.addView(tv);


        listView.addFooterView(footer);

        listView.setAdapter(adapter);
        //setContentView(R.layout.activity_lecture_refer_room);
    }
}

Therer are two .xml files.(one for activity that contains listview, one for footer) To add textview, I use setContentView(R.layout.refer_footer); and textview was added sucessfully. But when I run a app, it only displays the content of footer.(not listview) So I use setContentView(R.layout.activvity_lecture_refer_room); then app displays nothing.

What should i do to display lsitview containing footer?


Solution

  • Here:

    setContentView(R.layout.refer_footer);
    

    No need to call setContentView with refer_footer layout because refer_footer layout is for ListView footer which you are adding using addFooterView :

    // inflate foooter layout 
     View footer = getLayoutInflater().inflate(R.layout.refer_footer,
                                                                 null, false);
      // get footer_layout from footer
      LinearLayout ll = (LinearLayout)footer.findViewById(R.id.footer_layout);
        // create TextView
        TextView tv= new TextView(this);
        tv.setText(element.text());
        tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));
        tv.setVisibility(View.VISIBLE);
        // add textview to footer_layout
        ll.addView(textview);
        // set layout for footer
        listView.addFooterView(footer);