ankit joshi ankit joshi - 1 year ago 122
Android Question

id attribute in fragments

I am working on a app and it runs just fine but there is an problem that it crashes when I dont write id in my fragment code but runs fine after using id attribute and the problem is that i have not used it's id anywhere in my app

Here is the xml file

<?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="horizontal"
>
<fragment
class="com.hfad.workout.WorkoutList"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:id="@+id/listfrag"
/>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="second text view"
android:layout_marginTop="20dp"
android:id="@+id/fragcont"
android:layout_weight="3"
/>
</LinearLayout>


workoutlist.jav

public class WorkoutList extends ListFragment {

MainActivity ma;
static interface WorkoutListListener{
void clickme(long at);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

ArrayAdapter<Workout> arrayAdapter = new ArrayAdapter<Workout>(
inflater.getContext(), android.R.layout.simple_list_item_1,
Workout.workout);
setListAdapter(arrayAdapter);

return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onAttach(Context ac){
super.onAttach(ac);
this.ma =(MainActivity) getActivity();

}

public void onListItemClick(ListView v, View vi, int position, long id){
ma.clickme(id);

}
}

Answer Source

From official documents

Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download