如何在不进行单独活动的情况下制作自定义ListView?

时间:2015-08-11 17:49:36

标签: android

我一直在看的很多教程告诉我,我只需要创建一个只包含自定义列表的新活动,但我想在listview之前的右上角添加3个按钮

我有什么方法可以做到这一点吗?

3 个答案:

答案 0 :(得分:0)

如果教程告诉你需要为列表视图(也就是ListActivity)制作separete活动,那么它们就错了:)只需在xml中添加正常活动。

答案 1 :(得分:0)

内容布局文件可能如下所示:

<LinearLayout orientation=vertical>
  <LinearLayout orientation=horizontal>
    <your 3 buttons>
  </End of horizontal LinearLayout>
  <ListView/>
<End of vertical LinearLayout>

答案 2 :(得分:0)

@Thomas R.是对的 但是如果你想让列表与按钮一起滚动,那么就可以这样做了:

public class ListSomething extends ActionBarActivity {
  @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);
      .......
      ........
        ListView listV = (ListView) findViewById(R.id.listView);
        listV.setAdapter(yourListAdapter);
      
      //this is the most relevant part
      //you call it after you set the adapter
        setListViewHeightBasedOnChildren(listV);
      }
  
  
  public static void setListViewHeightBasedOnChildren(ListView listV) {
        YourListAdapter yourListAdapter = (YourListAdapter) listV.getAdapter();
        if (yourListAdapter == null)
            return;

        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listV.getWidth(), View.MeasureSpec.UNSPECIFIED);
        int totalHeight = 0;
        View view = null;
        for (int i = 0; i < yourListAdapter.getCount(); i++) {
            view = yourListAdapter.getView(i, view, listV);
            if (i == 0)
                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));

            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listV.getLayoutParams();
        params.height = totalHeight + (listV.getDividerHeight() * (yourListAdapter.getCount() - 1));
        listV.setLayoutParams(params);
        listV.requestLayout();
    }

然后在你的xml中:

<ScrollView>
<LinearLayout orientation=vertical>
  <LinearLayout orientation=horizontal>
    <your 3 buttons>
  </End of horizontal LinearLayout>
  <ListView/>
<End of vertical LinearLayout>
<End of ScrollView>