Answer the question
In order to leave comments, you need to log in
Dynamic work with fragments?
On pressing the button, a fragment should appear, but nothing happens, what's the problem?
Here is the snippet code:
public class ProfileFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile,null);
}
}
public class WorkActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work);
}
public void onClick(View view) {
Fragment profileFragment = new Fragment();
FragmentTransaction fragt = getFragmentManager().beginTransaction();
fragt.add(R.id.mainLayout, profileFragment);
fragt.commit();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".Activity.WorkActivity">
<include layout="@layout/toolbar"
android:id="@+id/toolbar"></include>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mainLayout"
android:layout_alignTop="@+id/button"
android:orientation="horizontal"></LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_below="@+id/toolbar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="45dp"
android:onClick="onClick"
android:layout_marginStart="45dp" />
</RelativeLayout>
Answer the question
In order to leave comments, you need to log in
1) Are you using Fragment from support library( android.support.v4 ) or normal fragment ?
If from the library , then use getFragmentSupportManager()
instead getFragmentManager().beginTransaction()
of 2) Fragment profileFragment = new Fragment();
Masterpiece. Can you still create an instance of your fragment ?
3) The onClick method is called ( check with logs )?
4)
And the layout file itself:
R.id.mainLayout
? Is it a FrameLayout or a fragment that is inside the layout of the activity ? Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question