Fragment基本用法

1、定义两个Fragment,加载布局与Activity类似,leftFragment展示标题列表,点击列表,RightFragment展示详情

public class RightFragment extends Fragment {

    private TextView title;

    private TextView content;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_right, container, false);
        title = view.findViewById(R.id.content_title);
        content = view.findViewById(R.id.content_content);
        return view;
    }

    public void refresh(String title, String content) {
        this.title.setText(title);
        this.content.setText(content);
    }
}
public class LeftFragment extends Fragment {


    public LeftFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_left, container, false);
        RecyclerView recyclerView = view.findViewById(R.id.newsleft);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(new TitleListAdapter(initData()));
        return view;
    }

    private List<News> initData() {
        List<News> list = new ArrayList<>();
        for (int i = 0;i< 10;i++){
            News news = new News();
            news.setTitle("title" + i);
            StringBuilder builder = new StringBuilder();
            int max = new Random().nextInt(100);
            for (int j = 0;j<max;j++) {
                builder.append(j);
            }
            news.setContent(builder.toString());
            list.add(news);
        }
        return list;
    }

    class TitleListAdapter extends RecyclerView.Adapter<TitleHolder> {

        private List<News> list;

        public TitleListAdapter(List<News> list) {
            this.list = list;
        }

        @NonNull
        @Override
        public TitleHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            TitleHolder holder = new TitleHolder(LayoutInflater.from(getContext()).inflate(R.layout.news_title_layout, parent, false));
            holder.textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    News news = list.get(holder.getAdapterPosition());
                    RightFragment rightFragment = (RightFragment) getFragmentManager().findFragmentById(R.id.rightfragment);
                    rightFragment.refresh(news.getTitle(), news.getContent());
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull TitleHolder holder, int position) {
            News news = list.get(position);
            holder.textView.setText(news.getTitle());
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
    }

    class TitleHolder extends RecyclerView.ViewHolder{

        private TextView textView;

        public TitleHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.newstitle);
        }
    }
}

2、Activity引用

<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"
    tools:context=".four.NewsActivity">

    <fragment
        android:id="@+id/leftfragment"
        android:layout_width="0dp"
        android:name="com.example.firstlinecode.four.LeftFragment"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <fragment
        android:id="@+id/rightfragment"
        android:layout_width="0dp"
        android:name="com.example.firstlinecode.four.RightFragment"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>
public class NewsActivity extends AppCompatActivity {

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

    private void replace(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.leftfragment, fragment);
        transaction.commit();
    }
}

FragmentAndroid应用程序组件的一种,它允许将复杂的应用界面分解为更小、更独立的部分,每个Fragment代表应用中的一个功能区域或者视图。以下是Fragment基本使用步骤: 1. **创建Fragment**: 首先,你需要创建一个新的Fragment类,继承自`android.app.Fragment`或`androidx.fragment.app.Fragment`(适用于API 21及以上)。在类中可以设置初始化数据和布局。 ```java public class MyFragment extends Fragment { // ...你的代码... } ``` 2. **添加到Activity**: - 在你的Activity中,通过FragmentManager实例来管理Fragment。通常在`onCreateView()`或`onCreateOptionsMenu()`等生命周期方法中添加或替换Fragment。 ```java getSupportFragmentManager().beginTransaction() .add(R.id.container, new MyFragment()) .commit(); ``` 3. **处理事务**: 当需要显示、隐藏或替换Fragment时,使用`beginTransaction()`开始一个事务,然后调用相应的方法如`add()`, `replace()`, `hide()`, `show()`或`remove()`。 4. **通信与交互**: Fragment之间可以通过`getArguments()`, `setArguments()`传递数据,也可以通过`FragmentInteractionService`或`Callback`实现跨Fragment的通信。同时,Fragment和Activity之间可以使用`onActivityResult()`进行结果传递。 5. **生命周期管理**: 理解并响应Fragment的各个生命周期回调方法,比如`onAttach()`, `onCreateView()`, `onDestroyView()`等,以保证资源的有效管理和状态保存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值