Reputation: 31
I'm trying to use a CardView as a container for a menu; the card is populated with buttons. Is it possible to implement a click listener on each button without using a RecyclerView?
Applying a click listener on the buttons during creation, before being added to CardView and after being added to CardView is not working. Only the card itself remains clickable
Upvotes: 0
Views: 5278
Reputation: 938
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="app.module.taman.splash.mvp.SplashActivity">
<android.support.v7.widget.CardView
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:filterTouchesWhenObscured="true"
android:text="Click me !!" />
</android.support.v7.widget.CardView>
</RelativeLayout>
Code
Button button = (Button) findViewById(R.id.button);
CardView cardView = (CardView) findViewById(R.id.card);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(SplashActivity.this, "ButtonClicked", Toast.LENGTH_SHORT).show();
}
});
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(SplashActivity.this, "card clicked", Toast.LENGTH_SHORT).show();
}
});
Upvotes: 1
Reputation: 336
In this example , two buttons are added on a cardview , where each view has separate click listener. You can try this-
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private String TAG = "MainActivity";
Button btn_first, btn_second;
CardView cardView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cardView = (CardView) findViewById(R.id.cardview);
cardView.setOnClickListener(this);
btn_first = (Button)findViewById(R.id.btn_first);
btn_second = (Button)findViewById(R.id.btn_second);
btn_first.setOnClickListener(this);
btn_second.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_first:
Toast.makeText(this, "First Button", Toast.LENGTH_SHORT).show();
break;
case R.id.btn_second:
Toast.makeText(this, "Second Button", Toast.LENGTH_SHORT).show();
break;
case R.id.cardview:
Toast.makeText(this, "CardView", Toast.LENGTH_SHORT).show();
break;
}
}
}
Upvotes: 1