使用CardView将setOnItemClickListener上的片段更改为ListView

时间:2018-12-29 10:45:07

标签: android listview arraylist cardview

我有一个ListView,它使用CardView来放大其布局。当用户单击ListView中的第一项时,这将更改Fragment。但是,我不确定如何执行此操作。我试图更改适配器类(CustomAdapter.java)中的Fragment,但它不起作用。我也尝试过在ListView所在的Fragment中执行此操作,但它也不起作用(当我单击其中一项时,应用程序也没有崩溃-什么也没发生):

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Fragment fragment = null;

            switch (position) {

                case 0:
                    fragment = new DesignsWorkshopFragment();

                    break;

            }

            if (fragment != null) {

                FragmentTransaction ft = getFragmentManager().beginTransaction();

                ft.replace(R.id.content_frame, fragment);

                ft.addToBackStack(null);

                ft.commit();
            }

        }
    });

SuppliersFragment.java:

public class SuppliersFragment extends Fragment {

CustomAdapter adapter;
ListView lv;


public SuppliersFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_suppliers, container, false);

    lv = view.findViewById(R.id.lvFragmentSuppliers);

    adapter = new CustomAdapter(getContext(), getData());
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Fragment fragment = null;

            switch (position) {

                case 0:
                    fragment = new DesignsWorkshopFragment();

                    break;

            }

            if (fragment != null) {

                FragmentTransaction ft = getFragmentManager().beginTransaction();

                ft.replace(R.id.content_frame, fragment);

                ft.addToBackStack(null);

                ft.commit();
            }

        }
    });

    return view;
}

private ArrayList getData() {

    ArrayList<SuppliersCardview> suppliersCardview = new ArrayList<>();

    SuppliersCardview s = new SuppliersCardview();
    s.setThumbnail(R.drawable.designs_workshop_logo);
    s.setName("Designs Workshop");
    suppliersCardview.add(s);

    s = new SuppliersCardview();
    s.setThumbnail(R.drawable.organic_clothing_logo);
    s.setName("Organic Clothing Industries");
    suppliersCardview.add(s);

    s = new SuppliersCardview();
    s.setThumbnail(R.drawable.suns_sewing_ltd);
    s.setName("Sun's Sewing Ltd");
    suppliersCardview.add(s);

    return suppliersCardview;
}}

CustomAdapter.java:

public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<SuppliersCardview> suppliersCardview;

public CustomAdapter(Context c, ArrayList<SuppliersCardview> suppliersCardview) {
    this.c = c;
    this.suppliersCardview = suppliersCardview;
}

@Override
public int getCount() {
    return suppliersCardview.size();
}

@Override
public Object getItem(int position) {
    return suppliersCardview.get(position);
}

@Override
public long getItemId(int position) {

    return position;
}

@Override
public View getView(final int position, View convertView, final ViewGroup parent) {

    if (convertView == null) {
        convertView = LayoutInflater.from(c).inflate(R.layout.cardview_layout, parent, false);
    }

    final SuppliersCardview s = (SuppliersCardview) this.getItem(position);

    ImageView imageView = convertView.findViewById(R.id.ivSupplierLogo);
    TextView textView = convertView.findViewById(R.id.tvSupplierName);

    imageView.setImageResource(s.getThumbnail());
    textView.setText(s.getName());

    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Attempted to change fragment here in a switch statement

        }
    });

    return convertView;
}

SuppliersCardview.java:

public class SuppliersCardview {

private String name;
private int thumbnail;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getThumbnail() {
    return thumbnail;
}

public void setThumbnail(int thumbnail) {
    this.thumbnail = thumbnail;
}}

SuppliersFragment XML:

<FrameLayout 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="com.miguelpeachey.marketplacesimulator.Fragments.SuppliersFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvBrowseSuppliersHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#bfbdbd"
        android:fontFamily="@font/nunito_sans"
        android:paddingBottom="5dp"
        android:paddingStart="10dp"
        android:paddingTop="10dp"
        android:text="Browse Suppliers"
        android:textSize="25sp" />

    <ListView
       android:layout_marginLeft="40dp"
        android:layout_marginRight="40dp"
        android:id="@+id/lvFragmentSuppliers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@color/colorTransparent"
        android:dividerHeight="20dip"/>

</LinearLayout>

CardView XML:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="40dp"
android:orientation="vertical"
app:cardPreventCornerOverlap="false"
app:ignore="NamespaceTypo"
card_view:cardBackgroundColor="#cccbcb"
card_view:cardCornerRadius="15dp"
card_view:cardElevation="5dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/ivSupplierLogo"
        android:layout_width="150dp"
        android:layout_height="120dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:src="@drawable/ic_launcher_background" />

    <TextView
        android:id="@+id/tvSupplierName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ivSupplierLogo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/brawler"
        android:text="Supplier"
        android:textColor="#232323"
        android:textSize="22sp" />


</RelativeLayout>

那么我该如何替换/更改使用CardView作为其布局的ListView项单击上的片段?别人的解决方案对我没有帮助。

我已使用this website作为教程来创建CardView并填充ListView的布局(此处的某些代码来自网站)。

3 个答案:

答案 0 :(得分:0)

您有了片段对象,现在您需要使用片段管理器,并用要显示的片段替换现有片段。

DesignsWorkshopFragment fragment2=new DesignsWorkshopFragment();
FragmentManager fragmentManager=getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_main,fragment2,"tag");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

仅创建片段的实例不会在活动中显示它。

答案 1 :(得分:0)

在活动内部添加和替换片段。您需要在ListView中单击项目视图时通知您的活动。这可以通过界面完成。

创建一个界面:

public interface ClickListener{
  public void onClick();
   }

在您的活动中实现此接口。当您创建Fragment时,请在片段的构造函数中传递“ this”作为引用。

  fragment = new DesignsWorkshopFragment(this);

在片段内部,您需要创建接口引用。

private ClickListener clickListener ;

内部片段初始化此接口引用

DesignsWorkshopFragment(ClickListener clickListener){
this.clickListener = clickListener;
}

现在,在创建适配器时执行相同的操作。

adapter = new CustomAdapter(getContext(), getData(),clickListener);

内部适配器创建并初始化接口引用。

 private ClickListener clickListener ;

 public CustomAdapter(Context c, ArrayList<SuppliersCardview> suppliersCardview,
                       ClickListener clickListener ) {
  this.c = c;
  this.suppliersCardview = suppliersCardview;
  this.clickListener = clickListener;
  }

,以及每当发生点击时。只需调用接口方法即可。

convertView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       clickListener.onClick();
    }
});

这将在您的活动的界面实现内部进行回调。在这里

public void onClick(){
 //write your code for adding or replacing fragment.
}

答案 2 :(得分:0)

我设法通过删除

来使其正常工作
convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

在我的 CustomAdapter.java 类中。