-1

I'm working an app that has a list of cardviews and I want each cardview to open a certain activity when tapped. I am not using any recyclerviews or adapters, I have just created a multiple cardview xml files and included them into my main xml in coordinatorlayout and collapsingtoolbarlayout. I have tried to create onClick event for individual cardviews but app keeps crashing. Following is my main.xml code:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:fitsSystemWindows="true"
            android:background="@drawable/pic3"
            android:id="@+id/profile_id"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

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

        <include layout="@layout/card_layout1" />

        <include layout="@layout/card_layout6"/>
        <include layout="@layout/card_layout4"/>
        <include layout="@layout/card_layout5"/>

    </LinearLayout>


</android.support.v4.widget.NestedScrollView>

One of my cardviews xml:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_alignParentTop="true"

        android:src="@drawable/categories"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/thumbnail"
        android:maxLines="3"
        android:padding="8dp"
        android:text="Categories"
        android:textColor="@color/white"

        android:textSize="22dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:maxLines="3"
        android:padding="8dp"
        android:text="Embedded systems is ba jksdhkah jksadh bdkbadkwuhs hfoh dn ajbd arh fbkjasd akuhwkjd nsajkbf a dsadjna hwd nlksn ahrja snasfb kjasba sna"
        android:textColor="@color/white"
        android:textSize="14dp" />

</RelativeLayout>

And my MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


private CollapsingToolbarLayout collapsingToolbarLayout=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);


    collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    collapsingToolbarLayout.setTitle(getResources().getString(R.string.user_name));

    dynamicToolbarColor();

    toolbarTextAppearance();


}



private void dynamicToolbarColor() {

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.elec);
    Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
        @Override
        public void onGenerated(Palette palette) {
            int mutedColor = palette.getMutedColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
            collapsingToolbarLayout.setContentScrimColor(mutedColor);
        }
    });
}

private void toolbarTextAppearance(){
    collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedbar);
    collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {


    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {



}

}

How can I implement onClick event for each of my cardviews without using recyclerview and adapters?

1 Answers1

0

It's a bad practice. But you can set tag to all card views, find them in code and set click listener:

in you main.xml

...

<LinearLayout
    android:id="@+id/cardsContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="10dp">

    <include layout="@layout/card_layout1" />

    <include layout="@layout/card_layout6"/>
    <include layout="@layout/card_layout4"/>
    <include layout="@layout/card_layout5"/>
</LinearLayout>
...

all in you card layouts must have tag:

<android.support.v7.widget.CardView
      android:tag="clickableCard"
      ...>

      ...

</android.support.v7.widget.CardView>

Than you need to find all views with thos tag clickableCard : (solution from here: Find all views with tag?)

private ArrayList<View> getViewsByTag(ViewGroup root, String tag){
ArrayList<View> views = new ArrayList<View>();
final int childCount = root.getChildCount();
for (int i = 0; i < childCount; i++) {
    final View child = root.getChildAt(i);
    if (child instanceof ViewGroup) {
        views.addAll(getViewsByTag((ViewGroup) child, tag));
    }

    final Object tagObj = child.getTag();
    if (tagObj != null && tagObj.equals(tag)) {
        views.add(child);
    }

}
return views;

}

in you MainActivity.java in the end of onCreate method you need to:

ArrayList<View> clickableViews = getViewsByTag(findViewById(R.id.cardsContainer), "clickableCard");
    for (int i = 0; i < clickableViews.size(); i++) {
        final Integer viewIndex = i;
        View cardView = clickableViews.get(i);
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewIndex == 0) {
                    // do work with first card
                }
                else if (viewIndex == 1) {
                    // do work with second card
                }
                ...
            }
        });
    }
Community
  • 1
  • 1
  • thank you! Works like a charm! actually, I have to meet a deadline and learning recyclerview was taking too much of my time so i decided to go with the old-fashioned way. anyway, thank you so much! – Tayyaba Taimur May 05 '16 at 18:28
  • thanks) please rate my answer, it's my first answer on stackoverflow :) – Juced Juced May 06 '16 at 03:46