安卓实现左侧列表选择项点击,右侧fragment切换

news2024/9/22 4:13:37

安卓实现左侧列表选择项点击,右侧fragment切换

问题背景

安卓日常开发中,有时候需要开发页面中,显示左侧会列表选择项,点击不同的选项后右侧切换fragment显示,本文将介绍实现的一个思路。

问题分析

要实现的效果如下:
在这里插入图片描述

问题解决

话不多说,直接上代码。
(1)activity布局文件如下,主要包括左侧的竖直列表和右侧的fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/mListview"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:background="#ebebeb"
        android:layout_height="match_parent"/>

    <FrameLayout
        android:id="@+id/mFrame"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="match_parent"/>

</LinearLayout>

(2)左侧列表item布局,item_left_list.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="match_parent">

    <LinearLayout
        android:id="@+id/ll_menu"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_line"
            android:layout_width="3dp"
            android:layout_height="match_parent"
            android:background="#ff0000"
            android:visibility="invisible"/>

        <TextView
            android:id="@+id/tv_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"/>

    </LinearLayout>

</LinearLayout>

(3)右侧fragment布局,代码如下:

<?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="match_parent">
    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="30dp"/>
</LinearLayout>

(4)对应activity文件,代码如下:

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;

import com.baorant.layoutdemo.R;
import com.baorant.layoutdemo.adapter.MyAdapter;
import com.baorant.layoutdemo.fragment.ItemFragment;
import com.baorant.layoutdemo.model.User;

import java.util.ArrayList;
import java.util.List;

public class LeftListViewAcitvity extends AppCompatActivity
        implements AdapterView.OnItemClickListener {

    ListView mListview;
    FrameLayout mFrame;
    // listview的数据集合
    List<User> mList = new ArrayList();
    List<Fragment> fragmentList = new ArrayList<>();
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_left_list_view_acitvity);
        initView();
        initData();
    }

    //    初始化数据
    private void initData() {
//        初始化左侧列表数据
        initLeftListData();
//        加载fragment
        initFragment();
//        默认选中页面1
        chooseListItem(0);
    }

    //    切换fragment
    private void chooseListItem(int position) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        隐藏所有的fragment
        for(int i = 0; i < fragmentList.size(); i++ ){
            Fragment fragment = fragmentList.get(i);
            transaction.hide(fragment);
        }
        transaction.show(fragmentList.get(position));
        transaction.commit();
    }

    private void initFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        ItemFragment showFragment = new ItemFragment();
        for(int i = 0; i < mList.size(); i++){
            Fragment fragment = showFragment.getShowFragment(mList.get(i).getName());
            fragmentList.add(fragment);
        }
        for(int i = 0; i < fragmentList.size(); i++){
            transaction.add(R.id.mFrame,fragmentList.get(i));
        }
        transaction.commit();
    }

    private void initLeftListData() {
        for(int i = 1; i <= 10; i++){
            mList.add(new User("页面" + i));
        }
        adapter = new MyAdapter(mList,this);
        mListview.setAdapter(adapter);
        mListview.setOnItemClickListener(this);
    }

    //  控件初始化
    private void initView() {
        mListview = findViewById(R.id.mListview);
        mFrame = findViewById(R.id.mFrame);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        点击item切换fragment
        chooseListItem(position);
        for(int i = 0; i < mList.size(); i++){
//            先把所有的item标记为未被选中
            mList.get(i).setChecked(false);
        }
//        找出被选中的item,把user中的ischecked属性改为true
        mList.get(position).setChecked(true);
//        刷新适配器
        adapter.notifyDataSetChanged();
    }
}

(5)左侧列表对应的adapter文件,代码如下:


import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baorant.layoutdemo.R;
import com.baorant.layoutdemo.model.User;

import java.util.List;

public class MyAdapter extends BaseAdapter {
    List<User> mList;
    Context context;

    public MyAdapter(List<User> mList, Context context) {
        this.mList = mList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return mList != null ? mList.size() : 0;
    }

    @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) {
        ViewHolder holder;
        if(convertView == null){
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_left_list, null);
            holder.tvText = convertView.findViewById(R.id.tv_text);
            holder.tvLine = convertView.findViewById(R.id.tv_line);
            holder.llMenu = convertView.findViewById(R.id.ll_menu);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        if(mList.get(position).isChecked()){
            holder.tvText.setTextColor(Color.RED);
            holder.tvLine.setVisibility(View.VISIBLE);
            holder.llMenu.setBackgroundColor(Color.WHITE);
        }else{
            holder.tvText.setTextColor(Color.BLACK);
            holder.tvLine.setVisibility(View.GONE);
            holder.llMenu.setBackgroundColor(Color.parseColor("#ebebeb"));
        }
        String name = mList.get(position).getName();
        holder.tvText.setText(name);
        return convertView;
    }
    class ViewHolder {
        LinearLayout llMenu;
        TextView tvText;
        TextView tvLine;
    }
}

(6)定义的fragment,代码如下:

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.baorant.layoutdemo.R;

public class ItemFragment extends Fragment {
    TextView tvText;
    private String name;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if(bundle != null){
            name = bundle.getString("name");
        }
    }

    public static Fragment getShowFragment(String name){
        ItemFragment showFragment = new ItemFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name",name);
        showFragment.setArguments(bundle);
        return showFragment;
    }

    @SuppressLint("MissingInflatedId")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_show,null);
        tvText = view.findViewById(R.id.tv_content);
        tvText.setText(name);
        return view;
    }
}

问题总结

本文介绍了安卓开发中,左侧显示列表选择项,点击不同的选项后右侧切换fragment显示的一种方案,有兴趣的同学可以进一步深入研究。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/511383.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

前端三剑客 HTML+CSS+JS

文章目录 一、HTML1.1 基础标签1.2 列表1.3 表格1.4 表单 二、CSS2.1 引入方式2.2 CSS 选择器2.2.1 基本选择器2.2.2 组合选择器 2.3 常用属性2.3.1 背景2.3.2 文本2.3.3 字体2.3.4 display元素类型2.3.5 浮动2.3.6 盒子模型 三、JavaScript3.1 引入方式3.2 数据类型3.2.1 数组…

tomcat集群下的session共享和负载均衡

环境 操作系统&#xff1a;windows tomcat1&#xff1a;Apache Tomcat/7.0.52&#xff08;8085&#xff09; tomcat2&#xff1a;Apache Tomcat/7.0.52&#xff08;8086&#xff09; jre&#xff1a;1.7.0_80 nginx&#xff1a;nginx-1.20.1&#xff08;8070&#xff09; redis…

cmd@快捷键方式@静默执行命令@修复桌面空白快捷方式图标

文章目录 ref前言快捷方式执行命令行或打开文件eg:直接打开某个文件 创建快捷方式eg:快捷方式运行命令 修复快捷方式图标空白问题逐个修复批量修复一次性操作:逐步操作 执行效果第三方工具修复 ref How can I execute a Windows command line in background? - Super Userstb…

2022年5个不寻常的Web3预测

正如埃隆马斯克所说&#xff0c;“最有趣的结果是最有可能的”。所以&#xff0c;这是我对web3的5个不同寻常的预测&#xff0c;下面我将详细介绍我是如何得出这些想法的&#xff1a; 口袋妖怪训练师将是一份全职工作有人会使用JPEG支持的贷款购买房屋(IRL)DAO将收购一家上市公…

并发编程11:Synchronized与锁升级

文章目录 11.1 面试题11.2 Synchronized的性能变化11.3 Synchronized锁种类及升级步骤11.3.1 多线程访问情况11.3.2 升级流程11.3.3 无锁11.3.4 偏锁11.3.5 轻锁11.3.6 重锁11.3.7 小总结 11.4 JIT编译器对锁的优化11.4.1 JIT11.4.2 锁消除11.4.3 锁粗化 11.5 小总结 11.1 面试…

电影《银河护卫队3》观后感

上周看了电影《银河护卫队3》&#xff0c;本部电影&#xff0c;主要是围绕着主角团队中的一个队员展开叙事的&#xff0c;在团队中&#xff0c;这名队员叫“火箭”&#xff0c;是一只经过基因改造过的浣熊。 当初进行改造的团队&#xff0c;是一家拥有基因改造技术的团队&…

基于SpringBoot, Vue实现的校园二手书交易系统

背景 在Internet高速发展的今天&#xff0c;计算机的应用几乎完全覆盖我们生活的各个领域&#xff0c;互联网在经济&#xff0c;生活等方面有着举足轻重的地位&#xff0c;成为人们资源共享&#xff0c;信息快速传递的重要渠道。在中国&#xff0c;网上管理的兴起也同时飞速发…

Solidity中哈希函数的编码与解码

起因 写这篇文章的起因&#xff0c;是我在前端调试合约的时候&#xff0c;发现合约报错了&#xff0c;点开命令行报错&#xff0c;发现返回的是合约的 callData&#xff0c;我直接表演一个眼前一黑&#xff0c;我怎么直接的知道是调用哪个方法的时候报错呢&#xff1f; 于是有…

【网络基础知识概念】路由器,交换机,无线AP,DHCP,DNS,WAN接口和LAN接口是什么?(附实物图详解)

【写在前面】其实在做一些试题的时候&#xff0c;经常会有些概念性的东西完全不清楚&#xff0c;今天我就带大家整理一下&#xff0c;交换机是啥&#xff1f;路由器是啥&#xff1f;无线AP是啥&#xff1f;ADSL又是什么&#xff0c;啥叫DHCP&#xff0c;DNS又是啥&#xff1f;W…

改进YOLOv5 | C3模块改动篇 | 轻量化设计 |骨干引入动态卷积|CondConv

CondConv: Conditionally Parameterized Convolutions for Efficient Inference 卷积是当前CNN网络的基本构成单元之一,它的一个基本假设是:卷积参数对所有样例共享。作者提出一种条件参数卷积,它可以为每个样例学习一个特定的卷积核参数,通过替换标准卷积,CondConv可以提…

shell脚本之“sort“、“uniq“、“tr“、“cut“命令详解

文章目录 sort命令uniq命令tr命令cut命令 sort命令 以行为单位对文件内容进行排序&#xff0c;也可以根据不同的数据类型来排序. 比较原则&#xff1a;从首字符向后&#xff0c;依次按ASCII码值进行比较&#xff0c;最后将他们按升序输出. 语法格式 sort [选项] 参数 cat …

c++ this指针

this指针介绍&#xff1a; c中成员变量和成员函数分开存储&#xff0c;每一个非静态成员函数只会有一个实例&#xff0c;多个同类型对象共用这一个成员函数。那么代码怎么区分哪个对象调用自己呢&#xff1f;this指针由此应运而生。 c通过提供对象指针&#xff0c;this指针。…

2020年下半年软件设计师下午试题

【试题四】希尔排序 【说明】 希尔排序算法又称最小增量排序算法&#xff0c;其基本思想是&#xff1a; 步骤1 :构造一个步长序列delta、deltak、 deltak &#xff0c;其中delta1n/2 &#xff0c;后面的每个delta是前一个的1/2 &#xff0c; deltak1&#xff1b; 步骤2 :根…

【shell脚本里的命令】

目录 一、sort命令1.1、命令演示 二、unip命令1、命令演示1、列题:2、使用脚本来查看用户有没有被恶意登录&#xff0c;查看登录用户的对应ip地址 三、tr命令1.1、命令演示1.2、使用tr命令对数组进行排序 五、从Windows里拉文件到Linux系统中要做的潜在条件六、cut命令 一、sor…

vue 阻止事件冒泡和捕获

文章目录 1. js 事件的三阶段2. js 阻止事件冒泡&#xff0c;捕获3、JavaScript基础知识&#xff1a;preventDefault和stopPropagationpreventDefault()事件方法stopPropagation()事件方法 click.stop : 阻止事件冒泡 click.prevent : 阻止事件默认行为 click.self : 事件只作用…

卡尔曼滤波器-公式推导 | 原理分析 | 将卡尔曼滤波器在MatLab中简单实现

目录 1.状态转移2.协方差矩阵3.噪声协方差矩阵的传递4.观测矩阵5.状态更新6.噪声协方差矩阵的更新7.在MatLab中实现卡尔曼滤波器1.状态转移 卡尔曼滤波器又称为最佳线性滤波器。优点有实现简单、纯时域滤波器、不需要进行频域变换等。 假设有一辆汽车在路上行驶,用位置和速度…

《学会提问》读后感

文章目录 批判性思维是什么&#xff1f;《学会提问》讲了什么&#xff1f;怎么成为一个批判性思维者&#xff1f; 批判性思维是什么&#xff1f; ​ 批判性思维是什么&#xff1f;在接触之前我是没有概念的&#xff0c;先借用百度百科一句话&#xff1a;批判性思维&#xff08…

Android 引入hunter-timing监测UI主线程函数运行时耗时,Java(2)

Android 引入hunter-timing监测UI主线程函数运行时耗时&#xff0c;Java&#xff08;2&#xff09; &#xff08;1&#xff09;在工程的根build.gradle文件配置&#xff1a; buildscript {repositories {mavenCentral()}dependencies {classpath cn.quinnchen.hunter:hunter-t…

c语言实现三子棋(思路+项目展示+源代码)

&#x1f4d5;博主介绍&#xff1a;目前大一正在学习c语言&#xff0c;数据结构&#xff0c;计算机网络。 c语言学习&#xff0c;是为了更好的学习其他的编程语言&#xff0c;C语言是母体语言&#xff0c;是人机交互接近底层的桥梁。 本章来写一个三子棋小游戏吧。 让我们开启c…

java版本微信机器人使用教程V1.0

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号雄雄的小课堂 现在是&#xff1a;2023年5月10日17:57:02 前言 历经好多天&#xff0c;java版本的微信机器人终于写完了初版了&#xff0c;接下来开放注册&#xff0c;大家先试用一下&#xff0c;有问题可以提出来&a…