Android – View No ID – Why?… here is a solution to the problem.
Android – View No ID – Why?
I have a class that should call another activity based on the clicked button. This is done by checking the available IDs.
My problem is: the View passed to my class has no ID, or rather, it has a value of NO_ID. What confuses me is that the View as a button does have an ID.
public class StrengthOrganizer extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_strength_organizer);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_strength_organizer, menu);
return true;
}
public void notifyActivity(View view) {
Intent intent = null;
int id = view.getId();
switch(id){
case R.id.button_log_book_launcher:
intent = new Intent(this, LogBook.class);
break;
case R.id.button_programming_launcher:
intent = new Intent(this, Programming.class);
break;
case R.id.button_visualizer_launcher:
intent = new Intent(this, Visualizer.class);
break;
default:
return;
}
startActivity(intent);
}
}
The corresponding XML file is as follows:
<?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"
android:orientation="vertical" >
<Button android:name="@+id/button_log_book_launcher"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:text="@string/button_log_book_launcher"
android:onClick="notifyActivity" />
<Button android:name="@+id/button_programming_launcher"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:text="@string/button_programming_launcher"
android:onClick="notifyActivity" />
<Button android:name="@+id/button_visualizer_launcher"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:text="@string/button_visualizer_launcher"
android:onClick="notifyActivity" />
</LinearLayout>
Why is the View object given in the XML file without an ID?
Solution
You use android:name instead of android:id
in the XML to assign IDs. Use the latter instead.