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");
Related
How do I use the bottomNavigationView variable outside of the MainActivity?
In MainActivity, I would use this to set and reove a badge
// To Add
BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(menuItemId);
badge.setVisible(true);
// To remove
bottomNavigationView.removeBadge(menuItem.getItemId());
However it will return null in a fragment if I try the same method
public BottomNavigationView bottomNavigationView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MainActivity main = new MainActivity();
main.bottomNavigationView.removeBadge(2131231026);
I have also tried this in the fragment, but nothing occurs
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_chat, container, false);
final View nav = inflater.inflate(R.layout.activity_main, container, false);
bottomNavigationView = nav.findViewById(R.id.bottomNav);
BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(2131231026);
badge.setVisible(false);
I don't know if you have this in Java (requireActivity) and if you have only one Activity in your project, but It can be the solution :
(requireActivity() as MainActivity).findViewById(R.id.bottomNav)
Also you can add function in your main Activity like addBadge / removeBadge.
But I think you can't get bottomNavigationView outside the main activity because it's part of UI mainActivity and not others fragments
PS : Your line " MainActivity main = new MainActivity();" isn't good because you instanciate an activity and not get actual instance so bottomNavigationView is null. May be use this.getActivity() ( this = fragment instance)
If you want to use BottmNavigationView outside of MainActivity first you should create a separate activity like MenuActivity and suppose you want to use 5 items in BottmNavigationView, so:
public class MenuActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
final Fragment fragment1 = new DiscoverFragment();
final Fragment fragment2 = new CreateFragment();
final Fragment fragment3 = new AnalyticsFragment();
final Fragment fragment4 = new MoreFragment();
final FragmentManager fm = getSupportFragmentManager();
final Fragment[] active = {fragment1};
fm.beginTransaction().add(R.id.main_container, fragment4, "4").hide(fragment4).commit();
fm.beginTransaction().add(R.id.main_container, fragment3, "3").hide(fragment3).commit();
fm.beginTransaction().add(R.id.main_container, fragment2, "2").hide(fragment2).commit();
fm.beginTransaction().add(R.id.main_container,fragment1, "1").commit();
bottomNavigationView=findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
fm.beginTransaction().hide(active[0]).show(fragment1).commit();
active[0] = fragment1;
return true;
case R.id.add:
fm.beginTransaction().hide(active[0]).show(fragment2).commit();
active[0] = fragment2;
return true;
case R.id.chart:
fm.beginTransaction().hide(active[0]).show(fragment3).commit();
active[0] = fragment3;
return true;
case R.id.more:
fm.beginTransaction().hide(active[0]).show(fragment4).commit();
active[0] = fragment4;
break;
}
return true;
}
});
}
}
XML view:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<FrameLayout
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="MainActivity"
tools:showIn="#layout/activity_main"
android:padding="1dp"
android:id="#+id/main_container"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
app:itemIconSize="26dp"
app:itemTextAppearanceActive="#style/BottomNavigationView.Active"
app:itemTextAppearanceInactive="#style/BottomNavigationView"
app:itemIconTint="#drawable/navigation_view_colored"
app:itemTextColor="#drawable/navigation_view_colored"
app:labelVisibilityMode="labeled"
android:layout_gravity="bottom"
android:background="#android:color/white"
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="#menu/bottom_navigation_menu" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
be sure you created 5 fragments like DiscoverFragment, CreateFragment, and so on ...
and XML view of them.
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();
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;
}
}
So I have a fragment with the following in the XML layout file:
<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="com.example.dwinnbrown.myapplicationv20.MainFragment">
<!-- TODO: Update blank fragment layout -->
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I am now trying to load a url into the web view through the java file associated with the fragment. However I am running into an error "cannot resolve findViewByID(int)". Any ideas?
Here is the code I am trying to use for the fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
/**
* A simple {#link Fragment} subclass.
*/
public class MainFragment extends Fragment {
public MainFragment() {
// 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_main, container, false);
String url = "http://winn-brown.co.uk/";
WebView view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
}
}
Do Something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String url = "http://winn-brown.co.uk/";
WebView view = (WebView) rootView.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
return rootView ;
}
Below is the xml for fragment:
<?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=".WebActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/webview">
</WebView>
</RelativeLayout>
And try this for fragment class
public class MainFragment extends Fragment {
WebView webView;
public MainFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
webView=(WebView)getActivity().findViewById(R.id.webview);
WebSettings webSettings=webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("your_url");
webView.setWebViewClient(new Mybrowser());
if (savedInstanceState != null)
webView.restoreState(savedInstanceState);
else
webView.loadUrl("your_url");
}
private class Mybrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
String url = "http://winn-brown.co.uk/";
WebView wv = (WebView) view.findViewById(R.id.webView);
wv.setWebViewClient(new WebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl(url);
}
I have a ViewPager in which I am able to view between 4 different tabs (which are fragments) I created. In one of my fragments, I want to have a button that will, after I click a button on that page, replace that view with another fragment. Now I don't want to swipe to another tab, I just merely want to replace the view of the current fragment when I press that button. Here is my attempt, but I'm not sure why when I click my button, nothing happens. If anyone could help me that would be great. Thanks!
This is the Fragment I call to create the view and the button I want to press.
ManualSelection.java
public class ManualSelection extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_manual_selection, container, false);
intent = new Intent(getActivity(), ManualSelectionListView.class);
return rootView;
}
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button listViewGenerated = (Button) getActivity().findViewById(R.id.manual_generate);
listViewGenerated.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
});
}
}
And here is the Fragment I want to create
ManualSelectionListView.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ManualSelectionListView extends Fragment {
static final String[] MOBILE_OS =
new String[] { "Android", "iOS", "WindowsMobile", "Blackberry"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.listview, container, false);
ListView lv = (ListView)rootView.findViewById(R.id.listview);
lv.setAdapter(new MobileArrayAdapter(getActivity(),MOBILE_OS));
return rootView;
}
}
And here are my XML files:
activity_manual_selection.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.ecs160.homestay.ManualSelection"
android:id="#+id/fragmentTest">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate"
android:id="#+id/manual_generate"
android:layout_centerHorizontal="true"
android:onClick="generateListView"/>
And here is the XML file called listview.xml that contains R.id.listView_manual
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView_manual">
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
I get nothing displayed when I hit "Generate." Any ideas? Thanks!
In your Activity you should create this:
public void generateListView(View v){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
The problem is that you are trying to get the Button id from your main activity which will return null
Button listViewGenerated = (Button) getActivity().findViewById(R.id.manual_generate);
Button manual_generate is located in your activity_manual_selection layout not in your Main activity's layout you cant get view from different layout or else it will return null
solution:
Get the Button's id from your fragment's layout
public class ManualSelection extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_manual_selection, container, false);
intent = new Intent(getActivity(), ManualSelectionListView.class);
Button listViewGenerated = (Button) rootView.findViewById(R.id.manual_generate);
listViewGenerated.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
});
return rootView;
}
remove onActivityCreated