在Android studio中使用Listview控件和Fragment编写出三行两列的页面
时间: 2024-02-03 09:11:27 浏览: 114
首先,需要在XML布局文件中添加一个ListView控件和一个Fragment容器:
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ListView
android:id="@+id/listView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"/>
</LinearLayout>
```
然后,在Fragment容器中添加一个GridView控件,并设置适配器:
```
public class MyFragment extends Fragment {
GridView gridView;
public MyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
gridView = view.findViewById(R.id.gridView);
gridView.setAdapter(new MyAdapter(getActivity()));
return view;
}
private class MyAdapter extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
public MyAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return 6;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_item, parent, false);
}
ImageView imageView = convertView.findViewById(R.id.imageView);
TextView textView = convertView.findViewById(R.id.textView);
imageView.setImageResource(R.drawable.ic_launcher_background);
textView.setText("Item " + (position + 1));
return convertView;
}
}
}
```
最后,在MainActivity中设置ListView的适配器,并在列表项点击时切换Fragment:
```
public class MainActivity extends AppCompatActivity {
ListView listView;
FrameLayout fragmentContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
fragmentContainer = findViewById(R.id.fragmentContainer);
listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new String[]{"Fragment 1", "Fragment 2", "Fragment 3"}));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new MyFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, fragment);
transaction.commit();
}
});
}
}
```
注意要修改MyAdapter中的数据源和布局文件,以及在GridView中设置列数。
阅读全文