How to use getActivity () method in Fragment?
This code takes off for me java.lang.RuntimeException: Unable to start activity ComponentInfo
public class Fragment1 extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment1, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ((Button)getActivity().findViewById(R.id.btnFind)).setText("Access from Fragment1"); } }); return v; } } Activity.java
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//java.lang.RuntimeException: Unable to start activity ComponentInfo } } activity_main.xml
<?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:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/btnFind" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="find"> </Button> <fragment android:id="@+id/fragment1" android:name="com.my_research_app.fragment_getactivity2.Fragment1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" tools:layout="@layout/fragment1"> </fragment> <FrameLayout android:id="@+id/fragment2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"> </FrameLayout> </LinearLayout> }
fragment1.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#77ff0000" android:orientation="vertical"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="frag1_text"> </TextView> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="log"> </Button> </LinearLayout>
Viewfragment from the activit in this way and thegetActivity()method has nothing to do with it / It returns the current instance of the activity class in which the fragment is located, not its markup - pavlofffjava.lang.RuntimeException: Unable to start activity ComponentInfosays practically nothing. Show the full stack trace. - post_zeew