今天实现一下主页的列表视图,切换fragment的功能

fragment_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>

效果如下:

然后为每个子项添加布局 item.xml:

  <?xml version="1.0" encoding="utf-8"?>
  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical">
  <TextView
      android:id="@+id/text_view"
      android:layout_width="match_parent"
      android:layout_height="120dp"
      android:gravity="center"
      android:background="#c0c7c759"
      android:textSize="20sp" />
  </FrameLayout>

效果:

添加适配器 MyAdapt.java:

  import android.support.annotation.NonNull;
  import android.support.v7.widget.RecyclerView;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.TextView;
  import java.util.List;
  public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
  //数据源
  private List<String> mList;
  public MyAdapter(List<String> list) {
      mList = list;
      }
  //返回item个数
  @Override
  public int getItemCount() {
      return mList.size() ;
      }
  //创建ViewHolder
  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate     (R.layout.item, parent, false));
      }

  //填充视图
  @Override
  public void onBindViewHolder(@NonNull final MyAdapter.ViewHolder holder, final int position) {
      holder.mView.setText(mList.get(position));
  }
  public class ViewHolder extends RecyclerView.ViewHolder {
      public TextView mView;

      public ViewHolder(View itemView) {
          super(itemView);
          mView = itemView.findViewById(R.id.text_view);
          }
      }
  }

HomeFragment.java 关键代码:

private RecyclerView recyclerView;
private MyAdapter mMyAdapter;
private LinearLayoutManager mLayoutManager;
private List<String> list;
private FloatingActionButton fab_create,fab_switch;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public View onCreateView(@Nullable LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
    View v =inflater.inflate(R.layout.fragment_home,container,false);

    initData();
    recyclerView = v.findViewById(R.id.rv);

    mMyAdapter = new MyAdapter(list);
    mLayoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setAdapter(mMyAdapter);
    //添加分割线 (divider.xml) 
    DividerItemDecoration decoration = new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL);
    decoration.setDrawable(getResources().getDrawable(R.drawable.divider,null));
    recyclerView.addItemDecoration(decoration);

    fab_create= getActivity().findViewById(R.id.fab_create);
    fab_create.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getContext(), "create", Toast.LENGTH_SHORT).show();
            list.add("item");
            recyclerView.setAdapter(mMyAdapter);
        }
    });

    mListener.onFragmentInteraction(Uri.parse("home"));
    return v;
}

private void initData() {
    list = new ArrayList<>();
    for (int i = 0; i <= 2; i++) {
        list.add("Item " + i);
    }
}

分割线 divider.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:startColor="@color/white"
    android:endColor="@color/white"
    android:type="linear" />
<size android:height="5dp"/>
</shape>

最终效果:

MainActivity 关键代码:

private Fragment mContent;
private FragmentManager fm;
private SettingsFragment settingsFragment;
private HomeFragment homeFragment;

public void init() {
    settingsFragment=new SettingsFragment();
    homeFragment=new HomeFragment();

    fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add( R.id.container,homeFragment, "home" ).commit();
    mContent=homeFragment;
}

//切换fragment
public void switchContent(Fragment fragment){
    if (mContent!=fragment){
        FragmentTransaction transaction=fm.beginTransaction().setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out);
        if (!fragment.isAdded()) {
            transaction.hide(mContent).add(R.id.container,fragment).commit();
        }else {
            transaction.hide(mContent).show(fragment).commit();
        }
        mContent = fragment;
    }
}

//侧滑栏点击事件
fab_create= getActivity().findViewById(R.id.fab_create);
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    FragmentTransaction ft=fm.beginTransaction();
    int id = item.getItemId();
    switch (id){
        case R.id.nav_home:
            switchContent(homeFragment);
            break;
        case R.id.nav_settings:
            switchContent(settingsFragment);
            break;
        case R.id.nav_statistics:

    }
    ft.commit();
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

悬浮按钮点击事件 HomeFragment.java:

fab_create.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getContext(), "create", Toast.LENGTH_SHORT).show();
        list.add("item");
        recyclerView.setAdapter(mMyAdapter);
    }
});

注意一点就是,这里的悬浮按钮是添加在activity_main.xml中的,所以要用getActivity()获取它的id,在这里卡了半天

Last modification:July 21st, 2020 at 10:49 pm