Fragment wont show in activity - java

I am very new to android development. I went through several tutorials on fragments but for some reason i cant seem to add a fragment from my main view. I'm not trying to do anything painfully complicated. All I want is to create my fragments and add them to my main activity. That's it. But every time I run my application all I get is a blank screen. I debug it and it is going to the fragment. This leads me to believe that the issue may be in the xml laout file (maybe).
Here is my MainActivity.java
package com.android.myCompany.nameOfApp;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Begin the transaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.foo_frame_layout, new FooFragment());
ft.commit();
}
}
Here is my Fragment.cs
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class FooFragment extends Fragment {
public FooFragment () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setText(R.string.hello_blank_fragment);
return textView;
}
}
Here is my layout activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#drawable/background_portrait">
<FrameLayout
android:id="#+id/copyright_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
Here is my fragment_foo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/copyright_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FooFragment">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="102dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="8dp"
android:adjustViewBounds="false"
android:cropToPadding="false"
app:layout_constraintBottom_toTopOf="#+id/imageView6"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/logo" />
<ImageView
</RelativeLayout>
Can anyone tell me what is wrong with my set up? Many thanks in advance.

Change with this in your fragment class :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_foo, container, false); // This line will inflate your fragment_foo layout and return it's rootview for fragment inflation
}
and then find your fragment views in onViewCreated method of fragment.

Try adding this in your fragment class...
public static FooFragment newInstance()
{
return new FooFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_layout, container, false);
// work with your ui code here.
return view;
}
And call this method in your activity...
// Begin the transaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.foo_frame_layout, FooFragment.newInstance());
ft.commit();

Related

I can't seem to get my fragment to load webview without crashing

So I'm making an app where the bottom navigation lets you click through different web pages and I've come across a problem. I can't seem to get it where the webview will function correctly inside the fragment class.
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_container"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="56dp">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_clever.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/clever_web"></WebView>
</RelativeLayout>
cleverfragment.java (the one im currently working with)
package com.port.schoool;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
webview.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("google.com");
return inflater.inflate(R.layout.fragment_clever, null);
}
}
mainactivity.java
package com.port.schoool;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(this);
loadFragment(new ReadWorksFragment());
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fragment = new ReadWorksFragment();
break;
case R.id.navigation_dashboard:
fragment = new CleverFragment();
break;
case R.id.navigation_notifications:
fragment = new PortalFragment();
break;
}
return loadFragment(fragment);
}
}
Here is my logcat logs for the crashes:
2019-08-04 18:05:25.164 7425-7425/com.port.schoool E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.port.schoool, PID: 7425
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.webkit.WebView.findViewById(int)' on a null object reference
at com.port.schoool.CleverFragment.onCreateView(CleverFragment.java:20)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6960)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Replace your fragment with:
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_clever, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
webview = view.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("https://google.com");
}
}
Of note:
Your original code would not compile, as there is no findViewById() on Fragment
The right version of inflate() to use in onCreateView() is the one that takes the container and false as the second and third parameters
You configure your fragment's views in onViewCreated()
You need to call findViewById() on the inflated layout (view in onViewCreated()) and assign that to webview
You need to use a valid URL with loadUrl()
This sort of stuff should be covered in your book on Android app development.

Passing values among fragments through bundle

I am a beginner, new to android technology. Actually I tried to solve already existing question through different approach. I took 3 fragments in single activity, and in 1st fragment i took editText, in 2nd fragment I took button and after clicking on that button I tried to display the fragment1 data in 3rd fragment By passing value through Bundle and I got stuck. How to do this task by this approach.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/top"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
<FrameLayout
android:id="#+id/mid"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
<FrameLayout
android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
</LinearLayout>
MainActivity
package com.example.com.dynamicfragmentproject;
import android.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Top_fragment frg1=new Top_fragment();
transaction.add(R.id.top,frg1);
transaction.commit();
}
public void cacheData(String str) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Mid_fragment frg2=new Mid_fragment();
transaction.add(R.id.mid,frg2);
transaction.commit();
Bundle bundle = new Bundle();
bundle.putString("editText",str);
frg2.setArguments(bundle);
}
public void cacheData1(String name) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Bottom_fragment frg3=new Bottom_fragment();
transaction.add(R.id.bottom,frg3);
transaction.commit();
Bundle bundle = new Bundle();
bundle.putString("editText",name);
frg3.setArguments(bundle);
}
}
fragment1.xml
<?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=".Top_fragment">
<!-- TODO: Update blank fragment layout -->
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hello_blank_fragment"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#color/colorPrimary"/>
</RelativeLayout>
Fragment1.java
package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class Top_fragment extends Fragment {
private EditText editText;
View view;
public Top_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_top_fragment, container, false);
editText = view.findViewById(R.id.editText1);
String str = editText.getText().toString();
MainActivity main = (MainActivity) getActivity();
main.cacheData(str);
return view;
}
}
fragment2.xml
<?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=".Mid_fragment">
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#color/colorPrimary"
android:layout_centerVertical="true"
android:layout_centerHorizontal="false"
/>
</RelativeLayout>
Fragment2.java
package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class Mid_fragment extends Fragment {
private Button buttonSubmit;
View view;
public Mid_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mid_fragment, container, false);
buttonSubmit = view.findViewById(R.id.button1);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity main1 = (MainActivity) getActivity();
Bundle bundle = getArguments();
String name = bundle.getString("editText");
main1.cacheData1(name);
}
});
return view;
}
}
fragment3.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="#+id/bottom"
tools:context=".Bottom_fragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimary"
android:padding="10dp"
/>
</FrameLayout>
Fragment3.java
package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class Bottom_fragment extends Fragment {
private TextView viewText;
View view;
public Bottom_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_bottom_fragment, container, false);
viewText = view.findViewById(R.id.textView1);
Bundle bundle = getArguments();
String name = bundle.getString("editText");
viewText.setText(name);
return view;
}
}
In first fragment create a object of second fragment.
FragmentTwo fragmenttwo=new FragementTwo();
Bundle bundle = new Bundle();
bundle.putSerializable(object,"data")
fragmenttwo.setArguments(bundle);
In the second fragment
Bundle bundle = getArguments();
if(bundle != null){
SampleModel model = (SampleModel) bundle.getSerializable("data");
}
You need to change code in MainActivity, you commit() before set args. Change code in whole app like below
public void cacheData(String str) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Mid_fragment frg2=new Mid_fragment();
Bundle bundle = new Bundle();
bundle.putString("editText",str);
frg2.setArguments(bundle);
transaction.add(R.id.mid,frg2);
transaction.commit();
}
And get data on Fragment onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
You can commit a transaction using commit() only prior to the activity saving its state (when the user leaves the activity). If you attempt to commit after that point, an exception is thrown. This is because the state after the commit can be lost if the activity needs to be restored. For situations in which it's okay that you lose the commit, use commitAllowingStateLoss().
For more detail you may refer this link
Updated :
In your code pass bundle value is perfect but when you get string of editext in Mid_fragment
getArguments().getString("editText");
this getting empty that's why solution is you do not need to pass Top fragment value to Mid Fragment just edittext make static like this
change public static EditText editText
Top_fragment extends Fragment {
View view;
public static EditText editText;
}
and Mid_fragment add this
onClick(View v) {
if (Top_fragment.editText!=null)
strtext=Top_fragment.editText.getText().toString();
here is full code of Mid_fragment
public class Mid_fragment extends Fragment {
View view;
private Button buttonSubmit;
public Mid_fragment() {
// Required empty public constructor
}
String strtext="";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mid_fragment, container, false);
//strtext = getArguments().getString("editText");
buttonSubmit = view.findViewById(R.id.button1);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Top_fragment.editText!=null)
strtext=Top_fragment.editText.getText().toString();
MainActivity main1 = (MainActivity) getActivity();
main1.cacheData1(strtext);
}
});
return view;
}
}

Change toolbar according to Fragment

I want to change the top toolbar according to clicked fragment but it seems not working for me.
What I want is when I click the fragment, the top toolbar should change. For example, add a Add button and change the title of the toolbar for Create Fragment.
Fragment.java
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
View v = inflater.inflate(R.layout.fragment_event_created, container, false);
Toolbar toolbar123 = (Toolbar) v.findViewById(R.id.toolbar123);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar123);
//((MainActivity) getActivity()).getSupportActionBar().hide();
return v;
}
Fragment XML
<FrameLayout 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="com.example.rick.check_in.ui.EventCreatedFragment">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar123"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#131313"
android:minHeight="?attr/actionBarSize">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#00aaaaaa">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:text="Delete"
android:textColor="#fff"
android:textSize="16dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
You can do it like this way. onAttach(Activity) called once the fragment is associated with its activity.
public class YourFragment extends Fragment {
private MainActivity mainActivity;
private Toolbar toolbar123;
public YourFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mainActivity = (MainActivity)activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_event_created, container, false);
toolbar123 = (Toolbar)v.findViewById(R.id.toolbar123);
setupToolbar();
return v;
}
private void setupToolbar(){
toolbar123.setTitle(getString("Your Fragment Title"));
mainActivity.setSupportActionBar(toolbar123);
}
}

Android How to change fragment TextView using java in MainActivivity

I insert one fragment in activity_main.xml using java, i put fragment in linear layout in activity_main.
Fragment xml file has one textView.
How can i change TextView when app start from MainActivity using java, when app start and when it called onCreate?
I try few solution form stacoverflow but i can get this to work.
Emulator get crashed when he start to load app.
Here is activity_main.xml code:
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.android.fragment_promjenaviewprekojave.MainActivity">
<LinearLayout
android:id="#+id/linearLayoutFragment_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Here is Fragment code:
package com.example.android.fragment_promjenaviewprekojave;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
Here is xml file for that fragment who contain only 1 TextView
<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"
tools:context="com.example.android.fragment_promjenaviewprekojave.BlankFragment">
<TextView
android:id="#+id/fragmentTextView_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Here is the MainActivity.java from where I want to change fragment TextView
package com.example.android.fragment_promjenaviewprekojave;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BlankFragment objA = new BlankFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.linearLayoutFragment_id, objA);
fragmentTransaction.commit();
TextView textView = (TextView) findViewById(R.id.fragmentTextView_id);
textView.setText("We add text to fragment TextView");
}
}
In your BlankFragment code, change
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
to :
//Declare a member to hold a reference to your TextView
private TextView myTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_blank, container, false);
myTextView = (TextView) v.findViewById(R.id.fragmentTextView_id);
myTextView .setText("Whatever text you want");
return (v);
}
//Also declare a function to modify the text on your fragment
public void setCustomText(String str) {
if (myTextView != null) {
myTextView.setText(str);
}
}
Now back in your activity, you can call
objA.setCustomText("Hello World!");
Bare in mind that you will need to store a reference to objA in your activity, such as
private BlankFragment objA;
The onCreate will then be :
objA = new BlankFragment();
Lastly, this method works fine once the views are all in place and drawn.
If you're looking to change the text inside the fragment at creation, you will want to use a newInstance pattern on the fragment, where you can pass the text as an argument.
Something like this :
objA = BlankFragment.newInstance("Hello world");
Where newInstance is defined in your fragment as follow :
public static BlankFragment newInstance(String str) {
BlankFragment f = new BlankFragment();
Bundle args = new Bundle();
args.putString("TextTag", str);
f.setArguments(args);
return (f);
}
And then you can retrieve this value in the onCreate of your Fragment like this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_blank, container, false);
myTextView = (TextView) v.findViewById(R.id.fragmentTextView_id);
String text = getArguments().getString("TextTag", "");
myTextView .setText(text);
return (v);
}
In your xml, you should have a fragment container. Assuming the ID of this is fragment_id:
For support library,
BlankFragment blankFrag = (BlankFragment)getSupportFragmentManager().
findFragmentById(R.id.fragment_id);
Or else for non-support library Fragment:
BlankFragment blankFrag = (BlankFragment)getFragmentManager().
findFragmentById(R.id.fragment_id);
You will also need a public method in the BlankFragment class with a signature like setTextViewText(String text) and then call it from MainActivity like blankFrag.setTextViewText("my text");

Unable to replace fragment on button click

I'm trying to learn how to implement fragments in android.
So, I created two buttons and a fragment in the activity_main.xml.
If I click on the first button, fragment_one should be inflated,
similarly if I click the second button, fragment_two should be inflated.
But the issue is it doesn't replace the fragment.
When I debug the code, performClick() method in the View.class returns false.
Also there is no error in LogCat.
I'm unable to figure out what is the issue with the code.
Here's the activity_main.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:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/fragment1" />
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/fragment2" />
<fragment
android:id="#+id/fragment_place"
android:name="com.example.myfragmentwithbuttonapp.FragmentTwo"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Here's the fragment_one.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:orientation="vertical"
android:background="#00ffff">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="#string/thisisfragment1"
android:textStyle="bold" />
</LinearLayout>
Here's the fragment_two.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:orientation="vertical"
android:background="#ffff00">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/thisisfragment2"
android:textStyle="bold" />
</LinearLayout>
Here's the FragmentOne.java
package com.example.myfragmentwithbuttonapp;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_one, container, false);
}
}
Here's the FragmentTwo.java
package com.example.myfragmentwithbuttonapp;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTwo extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_two, container, false);
}
}
Here's the MainActivity.java
package com.example.myfragmentwithbuttonapp;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Fragment fr;
FragmentManager fm;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fr = new FragmentOne();
fm = getFragmentManager();
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fr = new FragmentTwo();
fm = getFragmentManager();
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
});
}
}
I hope I have been able to explain the problem.
Any help is appreciated.
Thanks
For fragmentTransaction.replace() you need to specify a container for your fragment and the fragment itself. The container is the parent view which is going to hold your fragment. Tipically a FrameLayout.
Right now you are passing R.id.fragment_place as the container, but that id refers to a fragment and not to a fragment container.
In activity_main.xml, replace:
<fragment
android:id="#+id/fragment_place"
android:name="com.example.myfragmentwithbuttonapp.FragmentTwo"
android:layout_width="match_parent"
android:layout_height="match_parent" />
with:
<FrameLayout
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent" />
It works fine like this. The rest of your code is OK.

Categories

Resources