I am new to android and is in need for some little help.I have a xml layout called fragment_home.xml which contains some images.I want to redirect the user to another page(fragment_about_sl.xml) when the user clicks on an image.Please tell me how to do that and where to place the codes.
fragment_home.xml(layout with the images)
<LinearLayout
android:id="#+id/home"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.sloid.destinations.navigationdrawerfragments.homeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/aboutslbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:src="#drawable/aboutsl"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_marginBottom="10dp"
android:src="#drawable/toplandmarks"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>
fragment_about_sl.xml(the layout that should be redirected once image is clicked)
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/aboutslscrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sloid.destinations.navigationdrawerfragments.aboutSLFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="250dp" />
<LinearLayout
android:id="#+id/SliderDots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/viewPager"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
I also added the java file if its necessary.
homeFragment.java(java file for fragment_home.xml)
public class homeFragment extends Fragment {
public homeFragment() {
// 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_home, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Destinations");
}
}
aboutSLFragment.java(java file for fragment_about_sl.xml)
public class aboutSLFragment extends Fragment{
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
TextView aboutsltext;
Button readmorebtn;
public aboutSLFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about_sl, container, false);
viewPager = (ViewPager) rootView .findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout)rootView.findViewById(R.id.SliderDots);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.non_active_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.non_active_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
aboutsltext=(TextView)rootView.findViewById(R.id.aboutsltext);
readmorebtn=(Button)rootView.findViewById(R.id.readmorebtn);
readmorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (readmorebtn.getText().toString().equalsIgnoreCase("Read More"))
{
aboutsltext.setMaxLines(Integer.MAX_VALUE);//your TextView
readmorebtn.setText("Read Less");
}
else
{
aboutsltext.setMaxLines(3);//your TextView
readmorebtn.setText("Read More");
}
}
});
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("About Sri Lanka");
}
code added to change the fragment
rootView.findViewById(R.id.aboutslbtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new aboutSLFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.home, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
logcat
30388-30388/com.example.sloid.destinations E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sloid.destinations, PID: 30388
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sloid.destinations/com.example.sloid.destinations.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.sloid.destinations.navigationdrawerfragments.homeFragment.onCreateView(homeFragment.java:30)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1234)
at android.app.Activity.performStart(Activity.java:6329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
Just add ids to those images and handle onclick events inside your fragment. You can find the image view using findViewById(R.id.'yourId');
And the onClick listener set: view.setOnClickListener(...);
As per My comment
Reference : Fragment replace
Fragment fragment = new aboutSLFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.home, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Tutorial : https://www.javacodegeeks.com/2013/06/android-fragment-transaction-fragmentmanager-and-backstack.html
You are new in android right, first of all you need to check Fragment detail
As you question you need to replace or add fragment as #Vishva Dave said
Follow this link
private void loadFragment(Fragment fragment) {
// create a FragmentManager
FragmentManager fm = getFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit(); // save the changes
}
First you need to add android:id="#+id/imageId" to the <ImageView ... in the xml, then in your homefragment add this code:
public class homeFragment extends Fragment {
View rootView;
public homeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_home, container, false);
rootView.findViewById(R.id.imageId).setOnClickListener(new OnClickListener(){
// go to the other fragment using fragmentTransaction
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments
different titles
getActivity().setTitle("Destinations");
}
}
Related
I have created an app which basically has navigation drawer and I wish to load an fragment "home" whenever the activity launches instead of main activity.
Any idea how to do it.
You can call this method to view Fragments. In your case call this method on your onCreate()
//Fragment Changer
public void changeFragment(Fragment targetfragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_fragment, targetfragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commitAllowingStateLoss();
}
Example Usage
changeFragment(new YourFragment());
Basic solution can be implementing something like the below code in your onCreate method.
// get fragment manager
FragmentManager fm = getFragmentManager();
// replace
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_layout, new HomeFragment());
ft.commit();
Your Activity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public String getHelloMessage() {
return "Hello!";
}
}
Your View:
public class MainView extends Fragment {
// Declarations
private Button testButton;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_view, container, false);
// Getting the reference of controller from Application
MainController mainController = Application.getInstance().getMainController();
// Initializing view objects
testButton = view.findViewById(R.id.test_button);
// Setting actions
testButton.setOnClickListener(mainController.getTestAction());
return view;
}
// Reference to the view Object
public Button getTestButton() {
return testButton;
}
Your main_activity.xm lto connect the fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/containerMainView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/mainView"
android:name="com.template.views.MainView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Your main_view.xml file your final view definition
<?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">
<Button
android:id="#+id/test_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="#string/say_hello" />
</RelativeLayout>
I've been searching the error for about 2 hours on google , i can't figure out what it's wrong . It just force closes when I tap the button "butonCap", I didn't work with fragments until now
ERROR:
java.lang.IllegalStateException: Could not find method butonCap(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'cap'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:423)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:380)
at android.view.View.performClick(View.java:6897)
at android.widget.TextView.performClick(TextView.java:12693)
at android.view.View$PerformClick.run(View.java:26101)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Butoane.java - i just made another java file because i can't write any code in the fragment java file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_fata);
final Button butonCap = (Button) findViewById(R.id.cap);
butonCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent butonCap = new Intent(Butoanele.this, capul.class);
Butoanele.this.startActivity(butonCap);
}
});
}
}
fragment_fata.xml - this is just one of the 2 fragments from navigation view
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".FragmentFata"
android:background="#drawable/fata">
<!-- TODO: Update blank fragment layout -->
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/cap"
android:layout_width="wrap_content"
android:layout_height="65dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:background="#drawable/button_outline"
android:paddingBottom="30dp"
android:onClick="butonCap"
android:text="Cap"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
You class should extends Fragment and inflate layout in onCreateView() callback.
Call getActivity().findViewById in onViewCreated() callback.
watch this guide
In fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fata, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
if (getView() == null) {
return;
}
final Button butonCap = (Button) getView().findViewById(R.id.cap);
butonCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getView().getContext(), capul.class);
startActivity(intent);
}
});
}
I am not able to set the text from Homefragment.java
Currently I have below xml files:
activity_main.xml
<LinearLayout
android:id="#+id/tab_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<include
android:id="#+id/ftr"
layout="#layout/tab" />
</LinearLayout>
<LinearLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</LinearLayout>
Now tab.xml
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
Now class files:
activity_main.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
initUI();
}
private void initUI() {
fragment = new HomeFragment();
}
HomeFragment.java
public class HomeFragment extends Fragment {
private TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
context = getActivity();
initUI(rootView);
return rootView;
}
private void initUI(View view) {
txt = (TextView)view.findViewbyid(R.id.txt1);
txt.setText("hello. test");
}
fragment_home.xml
<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"
>
....
</RelativeLayout
Error log:
Caused by: java.lang.NullPointerException
at com.xx.ew.fragment.HomeFragment.initUI(HomeFragment.java:112)
at com.xx.ew.fragment.HomeFragment.onCreateView(HomeFragment.java:99)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
at android.app.Activity.performStart(Activity.java:5356)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2340)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Now the issue is When I am trying to set text of Textview of tab.xml in homefragment class then it is not set the text and force close the app.
How can set the text of textview(txt1) of tab.xml from homefragment.java ?
Changed my answer
Call your fragment as follows in initUI() method of activity:-
private void initUI() {
fragment = new HomeFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.tab_bar, fragment);
fragmentTransaction.commit();
}
In Fragment change only one line which is in createView method
View rootView = inflater.inflate(R.layout.tab, container,
false);
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new HomeFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
HomeFragment.java
public class HomeFragment extends Fragment {
private Context context;
private TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
context = getActivity();
initUI(rootView);
return rootView;
}
private void initUI(View view) {
txt = (TextView) view.findViewById(R.id.txt1);
txt.setText("hello. test");
}
}
fragment_home.xml
<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" >
<include
android:id="#+id/ftr"
layout="#layout/tab" />
</RelativeLayout>
Try:
Make rootView a global variable. And then override the onStart method and call initUI from there.
I am creating a fragment in which I'm using a clickable linearLayout as a button
I have created all the necessary methods and implemented the OnClickListener interface to the class but when i click the layout nothing happens
Here is my LinearLayout and TextView from xml and java code.
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="50dip"
android:layout_weight="1"
android:clickable="true"
android:background="#drawable/button_layout"
android:layout_margin="1dip">
<LinearLayout
android:orientation="vertical"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="e"
android:textColor="#color/abc_primary_text_disable_only_material_dark"
android:gravity="top"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="π"
android:gravity="bottom"/>
</LinearLayout>
</LinearLayout>
The mainview TextView is
<TextView android:id="#+id/mainview"
android:layout_width="match_parent"
android:background="#color/button_material_light"
android:layout_height="60dip"
android:layout_weight="1"/>
Class code is
public class HomeFragment extends Fragment implements View.OnClickListener{
TextView mainView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainView = (TextView) getActivity().findViewById(R.id.mainview);
}
public static HomeFragment newInstance(int i){
HomeFragment homeFragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt("index", i);
homeFragment.setArguments(args);
return homeFragment;
}
public HomeFragment() {
// 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_home, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt("index"));
}
#Override
public void onClick(View view) {
mainView.setText("ghalib");
}
}
I also tried debugging the program and find out that the method is not called on clicking the Layout.
Thanks to rahul to remind me to pass the "this" Object in the setOnClickListener of the Clickable LinearLayout Which I'm using as the Button
So first I assign the id to the layout by android:id="#+id/pie"
then setting the listner in the code then the new code is
public class HomeFragment extends Fragment implements View.OnClickListener{
TextView mainView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainView = (TextView) getActivity().findViewById(R.id.mainview);
//This is the New Part
((LinearLayout)getActivity().findViewById(R.id.pie))
.setOnClickListener(this);
}
public static HomeFragment newInstance(int i){
HomeFragment homeFragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt("index", i);
homeFragment.setArguments(args);
return homeFragment;
}
public HomeFragment() {
// 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_home, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity)activity).
onSectionAttached(getArguments().getInt("index"));
}
#Override
public void onClick(View view) {
mainView.setText("ghalib");
}
}
I'm trying to change a Textview's text inside a fragment, but it gaves me a NullPointerException at the setName method.
I have already tried 2 ways to do this:
public class MemberFragment extends Fragment {
private TextView tvName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_member,container, false);
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
return view;
}
public void setName(String name) {
tvName.setText(name);
}
or:
public class MemberFragment extends Fragment {
private static TextView tvName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_member,container, false);
return view;
}
public void setName(String name) {
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
tvName.setText(name);
}
but none gave me success. Here is where I instantiate the fragment:
MemberFragment fragment = new MemberFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
fragment.setName(map.get(Tags.NAME));
and the fragment_member.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="#style/ActionBar.Transparent.MyStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="446dp" >
<TextView
android:id="#+id/tvProfileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</ScrollView>
Can someone help me?
Thanks.
view in your onCreateView method is the rootView of your fragment.
So just add the following code in your onCreateView method to change the text of your TextView:
((TextView)view.findViewById(R.id.tvProfileName)).setText("Your new text");
try this:
tvName = (TextView) view.findViewById(R.id.tvProfileName);
instead of :
tvName = (TextView) getView().findViewById(R.id.tvProfileName);