gpt4 book ai didi

java - 是否有等效于 `ListView.addHeaderView' 的 XML 标记?

转载 作者:搜寻专家 更新时间:2023-10-30 19:56:49 25 4
gpt4 key购买 nike

是否有一个 XML 标记,我可以在布局文件中使用它等同于 ListView.addHeaderView()

最佳答案

我按照您的要求编写了一个简单的 ListView

  1. value 文件夹的 attrs.xml 中声明自定义属性:

    <resources>
    <declare-styleable name="HeaderListViewFromXML">
    <attr name="headerView" format="reference"/>
    </declare-styleable>
    </resources>
  2. 创建 HeaderListViewFromXML 类扩展 ListView

    public class HeaderListViewFromXML extends ListView {
    private int headerId;

    public HeaderListViewFromXML(Context context) {
    this(context, null);
    }

    public HeaderListViewFromXML(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
    }

    public HeaderListViewFromXML(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.HeaderListViewFromXML, defStyle, defStyle);

    try {
    headerId = a.getResourceId(R.styleable.HeaderListViewFromXML_headerView, View.NO_ID);
    if (headerId != View.NO_ID) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View header = inflater.inflate(headerId, null);
    addHeaderView(header);
    }
    } finally {
    a.recycle();
    }
    }
    }
  3. layout.xml 中声明自定义 HeaderListViewFromXML

    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.example.rewidget.HeaderListViewFromXML
    android:id="@+id/listWithHeader"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_marginTop="60dp"
    android:background="#00FF00"
    // custom attribute. Point to layout in header1.xml
    app:headerView="@layout/header1" />
    </RelativeLayout>
  4. 在Activity中,像普通的ListView一样使用

    public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView list = (ListView) findViewById(R.id.listWithHeader);

    String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);

    list.setAdapter(adapter);
    }
    }

关于java - 是否有等效于 `ListView.addHeaderView' 的 XML 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13149264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com