On Click Listener Issue
I am working on Android app in Android Studio and I created Grid Layout with Card view. as on image below: I was able to make onClick listener to open my BMIActivity when user cli
Solution 1:
Since you have added views manually in layout file, you should assign id's to your cells (CardViews) and click listeners directly on them.
<androidx.cardview.widget.CardView
android:id="@+id/cvBMI"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="8dp"
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true">
.
publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener {
GridLayout mainGrid;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainGrid = (GridLayout) findViewById(R.id.mainGrid);
findViewById(R.id.cvBMI).setOnClickListener(this);
findViewById(R.id.cvCHO).setOnClickListener(this);
findViewById(R.id.cvH20).setOnClickListener(this);
findViewById(R.id.cvProtein).setOnClickListener(this);
findViewById(R.id.cvCalendar).setOnClickListener(this);
findViewById(R.id.cvSettings).setOnClickListener(this);
}
@OverridepublicvoidonClick(View view) {
switch (view.getId()) {
case R.id.cvBMI:
openBMIActivity();
break;
case R.id.cvCHO:
openCHOActivity();
break;
case R.id.cvH20:
openH2OActivity();
break;
case R.id.cvProtein:
openProteinActivity();
break;
case R.id.cvCalendar:
openCalendarActivity();
break;
case R.id.cvSettings:
openSettingsActivity();
break;
}
}
}
Solution 2:
WHat you can do is to add tags for each of the cards either via xml android:tag="h20" or through java code view.setTag("h20") while iterating over the view if its dynamically added. call the same click function for all with the arguement as view like openActivity(View view). And inside that switch based on tag like
switch(view.getTag){
case "H20:
doA()
break;
case "SOMETHING":
doB()
break;
}
Post a Comment for "On Click Listener Issue"