Androidstudio怎样将 textview和imagView显示在MainActivity的listview上,并且从listview的第二行开始显示,自定义适配器继承simpleadapter
时间: 2024-02-13 12:06:52 浏览: 71
首先,在res/layout文件夹下创建一个布局文件,命名为list_item.xml,包含一个TextView和一个ImageView组件。
```xml
<?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="horizontal"
android:padding="10dp">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="TextView"
android:textSize="16sp" />
</LinearLayout>
```
接下来,创建一个自定义适配器MyAdapter,继承SimpleAdapter,重写getView方法。
```java
public class MyAdapter extends SimpleAdapter {
private Context mContext;
private List<? extends Map<String, ?>> mData;
public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
mContext = context;
mData = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position >= 1) {
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
return view;
}
}
```
最后,在MainActivity中使用自定义适配器,并将数据传递给它。
```java
public class MainActivity extends AppCompatActivity {
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.listview);
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Map<String, Object> map = new HashMap<>();
map.put("text", "Text " + i);
map.put("image", R.mipmap.ic_launcher);
list.add(map);
}
String[] from = {"text", "image"};
int[] to = {R.id.textview, R.id.imageview};
MyAdapter adapter = new MyAdapter(this, list, R.layout.list_item, from, to);
mListView.setAdapter(adapter);
}
}
```
这样就可以在MainActivity的ListView上显示TextView和ImageView,并且从第二行开始显示。
阅读全文