Here is the Fragment.xml file. I created some elements (like TextView and ImageView). I assigned IDs to those elements.
<ImageView
android:id="@+id/ivContact"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="center_horizontal"
android:src="@drawable/contact" />
<TextView
android:id="@+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="TextView"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvTel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="TextView" />
-----------------------------------------------------------------------
Here is the Fragment.java file.
TextView tvName,tvTel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
Here is the MainActivity.java file. I want to access the IDs of Fragment.xml file. In the MainActivity.java file. But I'm unable to access the IDs. It showing errer. I'm stuck. I had try so many time. But not solved. I think this is old version to access the IDs. But I don't know how can I access the IDs in new version.
ERROR:@layout/activity_main does not contain a declaration with id tvName.
TextView tvName,tvTel;
EditText etName,etTel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvName = findViewById(R.id.tvName);
tvTel = findViewById(R.id.tvTel);
etName = findViewById(R.id.etName);
etTel = findViewById(R.id.etTel);
}
Normally you should never have to do that. If you want to communicate with the host activity you can use the
onAttachmethod from the fragment or simplyrequireActivity(). Look at the example below