Text view in fragment not changing colour - java

I'm trying to change the colour of text for my text view within my fragment of my activity but nothing changes because of this error:
Cannot find symbol method findViewById(int)
What can I do to resolve this?
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"
android:background="#color/black">
<TextView
android:id="#+id/WCBank_textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Medium"/>
</RelativeLayout>
Java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TabWCBankTerminus extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_wc_bank_terminus,container,false);
return v;
TextView txt = (TextView)findViewById(R.id.WCBank_textView1);
txt.setText(Html.fromHtml("<font color='#FFD300'>text0</font>" +
"<font color='#00A4A7'> text1</font>" +
"<font color='#E32017'> text2</font>" +
"<font color='#FFFFFF'> text3</font>"
));
}
}

Fragment does not define a findViewById() method, you need to use the View object (v) to call it.
The reasoning behind this is, the Fragment does not know anything about the layout until it's inflated. You're inflating the layout and returning a view object that contains information about the stuff you're trying to configure, so you need to invoke the method on the View object instead of the Fragment.
Change to:
TextView txt = (TextView)v.findViewById(R.id.WCBank_textView1);
Then you return v at the very end of your method, not before you make the configuration changes.
It should look like this when you're done:
public class TabWCBankTerminus extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_wc_bank_terminus,container,false);
TextView txt = (TextView)v.findViewById(R.id.WCBank_textView1);
txt.setText(Html.fromHtml("<font color='#FFD300'>text0</font>" +
"<font color='#00A4A7'> text1</font>" +
"<font color='#E32017'> text2</font>" +
"<font color='#FFFFFF'> text3</font>"
));
return v;
}
}

in your onCreateView you have two errors. First you are return statement has to be, in your case, the last one, otherwise the statements that follow are unreachable. Second you have to invoke findViewById through v. Differently from Activity, Fragment has no findViewById method
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_wc_bank_terminus,container,false);
TextView txt = (TextView)v.findViewById(R.id.WCBank_textView1);
txt.setText(Html.fromHtml("<font color='#FFD300'>text0</font>" +
"<font color='#00A4A7'> text1</font>" +
"<font color='#E32017'> text2</font>" +
"<font color='#FFFFFF'> text3</font>"
));
return v;
}

Related

Tabbed Activity Android Studio [duplicate]

This question already has answers here:
How do I "findViewById" with fragments?
(2 answers)
Closed 4 years ago.
I wanted to know something, I want to make an application on android with Tabbed Activity, I have everything done, but I have a problem, I want to put TextViews in one of the tab and it does not let me instantiate, if I put the
match = (TextView) findViewById (R.id.match);
The program tells me:
Can not resolve method 'findViewById (int)'
How could I do it? Is there any way?
package com.example.jose.firebaseimportante;
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 TabbedUsuarioFutbol extends Fragment{
public TabbedUsuarioFutbol() {}
private TextView partido1;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.futbol_tabbed_usuario, container, false);
return rootView;
match = (TextView)findViewById(R.id.match);
}
}
Change
match = (TextView)findViewById(R.id.match);
to
match = rootView.findViewById(R.id.match);
and
return rootView;
should be the last statement in your onCreateView method because any statement after a return statement is unreachable statement, i.e. it will never execute.
Your onCreateView method should look like this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.futbol_tabbed_usuario, container, false);
match = rootView.findViewById(R.id.match);
return rootView;
}

controlling a button in a fragment [duplicate]

This question already has answers here:
How to set onclick listener for a button in a fragment in android
(3 answers)
Closed 4 years ago.
I want to control button from fragment xml file in the fragment activity. In other activity we can easily control our button by findviewbyid method and after that we can apply setonclicklistener. But here in fragment how do i access the button and apply onclicklistener method.
My Fragment.java
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.LinearLayout;
/**
* A simple {#link Fragment} subclass.
*/
public class QuoteTypeFragment extends Fragment {
public QuoteTypeFragment() {
// Required empty public constructor
}
LinearLayout typeOne, typeTwo, typeThree, typeFour;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
return vv;
}
}
My Fragment.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:background="#3f525e"
tools:context=".QuoteTypeFragment">
<Button
android:id="#+id/submitbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"/>
</FrameLayout>
So here I want to control the submit button in fragment.java. How can I acces the button by findviewbyid or findfragmentbyid. And in fragment.java where do I use that code to access submitbutton.
in OnCreateView
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
button = vv.findViewById(R.id.submitbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return vv;
}
In your QuoteTypeFragment.java
1) Cast the widget by using the view. (view.findViewById()).
2) Set the onClickistener.
3) Implement View.OnClickListener and the onClick method.
public class QuoteTypeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
Button mSubmitButton = vv.findViewById(R.id.submitbutton);
mSubmitButton.setonClickListener(this);
return vv;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submitbutton:
// Control the button
break;
}
}
It is very easy to control button from fragment XML file in the fragment activity.
In your onCreateView use these lines,
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vv = inflater.inflate(R.layout.fragment_quote_type, container, false);
button = vv.view.findViewById(R.id.submitbutton);
return vv;
}

null point exception when trying to fetch data from openweathermap [duplicate]

This question already has answers here:
getView returning null when fragment has been created from an activity
(6 answers)
Closed 5 years ago.
I am trying to get sunrise and sunset time for my current location from openweathermap api. I am following this tutorial.
I have copied the entire Function.java in the tutorial and trying to use the data to update my ViewPagerAdapter's Fragment.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
TextView cityField = getView().findViewById(R.id.tv_city);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
rv.setNestedScrollingEnabled(true);
Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
}
});
asyncTask.execute("25.180000", "89.530000"); // asyncTask.execute("Latitude", "Longitude")
rv.setHasFixedSize(true);
MyAdapter adapter = new MyAdapter(new String[]{"Hello", "World"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
and I have named my target for the city name as tv_city:
<TextView
android:id="#+id/tv_city"
android:layout_toRightOf ="#+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="40sp"
android:text="Hello World"
android:textSize="30sp"
android:layout_marginBottom="5sp"
android:paddingLeft="5sp"
android:gravity="top" >
</TextView>
The problem is, possibly I am making some mistake to fetch the data, as I am getting nul exception error for this line:
TextView cityField = getView().findViewById(R.id.tv_city);
as:
Process: com.example.phocast, PID: 9820 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.phocast.BlankFragment.<init>(BlankFragment.java:17)
WIth my limited knowledge in java, I am unable to solve it.
Kindly help.
Update
actually, writing oncreateview as:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
rv.setNestedScrollingEnabled(true);
Weather_OWM.placeIdTask asyncTask =new Weather_OWM.placeIdTask(new Weather_OWM.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
TextView cityField = rootView.findViewById(R.id.tv_city);
cityField.setText(weather_city);
}
});
solves my problem, but i dont know if this is proper/good way to use final. I will be really grateful if someone shows me the way before closing it.
Your cityView line of code is just hanging out there, not in a method or anything. The NullPointer is coming from getView(). You can't find the view before onCreateView occurs and the inflater does its thing. Move it to onCreateView, anytime after View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
You need initialize the textView after:
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
After initialize the recyclerView you can write this:
cityField = rootView.findViewById(R.id.tv_city);

Fragments: how to change content?

I have a class that manages a fragment .. in a TextView I have to put the phone features, but because by mistake?
import android.os.Build;
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;
public class PageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page, null);
return view;
}
String model = Build.MODEL;
String product = Build.PRODUCT;
String androidOS = Build.VERSION.RELEASE;
String scheda = model+"\n"+androidOS+" \n "+product+"";
TextView text = (TextView) findViewById(R.id.textView3);
text.setText(scheda);
private TextView findViewById(int textview3) {
// TODO Auto-generated method stub
return null;
}
}
I did not understand a thing. I have three fragment, one of which is called Home, one faq and one about. How do I change the contents of the various "screens"?
Firstly you cannot have operations on objects in the main class body without a helper method in java. I also see when you are creating a reference to you TextView, you need to find the TextView from your inflated view, so the right way to do it would be something like
TextView text = (TextView)view.findViewById(R.id.textview3);
Lastly, when inflating the view, pass the ViewGroup as the parent for that view, and a false for the attachToRoot
You should have something like:
public class PageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page,container,false);
String model = Build.MODEL;
String product = Build.PRODUCT;
String androidOS = Build.VERSION.RELEASE;
String scheda = model+"\n"+androidOS+" \n "+product+"";
TextView text = (TextView) view.findViewById(R.id.textView3);
text.setText(scheda);
return view;
}
}
Hope that helps

Fragment and view

My application is divided into fragments, each with its own layout (.xml file).
When I start visualize the first fragment in the onCreate() method of my activity, I set the appropriate layout with setContentView(fragment_first). How do I change, for example, a TextView contained inside the second fragment (fragment_second)?
Generally speaking, a Fragment, or any Activity or View for that matter, should update its own internal UI controls. It's easier, and it's good design. Other classes/events may update the state of the Fragment's data, but it handles how that state is displayed.
Edit to answer commented question:
This is how to load a content view in a Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.pump_info, container, false);
return view;
}
in your onCreateView() method, you should assign all of the views you will need to access later to fields in your fragment class, like this,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
view = inflater.inflate(R.layout.xxx, container, false);
this.aTextView = (TextView)view.findViewById(R.id.a_text_view);
this.anImageView = (ImageView)view.findViewById(R.id.an_image_view);
...
}
you can then use aTextView, etc. at other places in the execution of your fragment.
It seems you set the xml file you intended for your first fragment in your activity.
What you should do in short is create a completely new class and have it extend android.support.v4.app.Fragment, also have your activity extend FragmentActivity instead of just Activity.
Then in your android.support.v4.app.Fragment class (which I shall call your fragment from now on) you should override the onCreateView(LayoutInflater inflate, ViewGroup container, Bundle savedInstanceState){} method and in this method you should put a line like this:
View view = inflater.inflate(R.layout.the_xml_layout_for_this_fragment, container, false); which inflates the layout of the fragment and plants it in the proper place in your activity's layout.
After this your need to return view;, but before you return this view you can do view.findViewById(R.id.id_of_a_view_from_the_xml_layout_file); in order to find an element and manipulate it.
You should create such a fragment class for each fragment you need in your app and have it inflate it's own xml layout file.
For more detailed instructions you can see http://www.youtube.com/watch?v=4BKlST82Dtg or other videos or written tutorials.
EDIT: here is a basic fragment class:
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;
public class MyFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the view:
View view = inflater.inflate(R.layout.myfrag_layout, container, false);
// manipulate widgets, for example:
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText("read me!!!");
// return the view:
return view;
}
}
and it's parenting activity:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class MyFragmentActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// notice that there is a different layout file for the activity and for
// the fragment!
setContentView(R.layout.xml_layout_for_the_activity);
// to start the fragment and stick it into your activity (not needed if
// you use ViewPager)
FragmentManager fragMan = getSupportFragmentManager();
fragMan.beginTransaction()
.add(R.id.the_visual_element_that_will_contain_your_fragments_layout, fragMan)
.commit();
}
}

Categories