trying to call method within a class extends Fragment, from a textview within
layout file. In an activity class I would use this:
setContentView(R.layout.activity_main);
What would I do to achieve similarity using a class extends Fragment?
Error from logcat:
java.lang.IllegalStateException: Could not find method mood(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatTextView with id 'moodtw'
Class :
public class Tab1 extends Fragment {
private View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab1, container, false);
return (rootView);
}
public void mood() {
String tempo;
int a;
TextView moodouttw = (TextView) rootView.findViewById(R.id.moodouttw);
tempo = moodouttw.getText().toString();
a = Integer.parseInt(tempo);
if (a < 5) {
a = a + 1;
} else a = 0;
tempo = Integer.toString(a);
moodouttw.setText(tempo);
}
}
COULDN'T GET ABOVE TO WORK, so I tried using onclicklistner found in a link from an prev. answer. This also with same error posted above. Looks like app is looking for a method with parameter which, to my knowledge, cant be set in a xml layout file.(?). I might try another approach.Below is copy of last approach and snippet from layout xml file. Thanks to all for help given.
package com.example.android.xxxxx;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Tab1 extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab1, container, false);
TextView t = (TextView) v.findViewById(R.id.anxietyouttw);
t.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.anxietyouttw:
// do something
String tempo;
int a;
TextView anxietyouttw = (TextView) v.findViewById(R.id.anxietyouttw);
tempo = anxietyouttw.getText().toString();
a = Integer.parseInt(tempo);
if (a < 5) {
a = a + 1;
} else a = 0;
tempo = Integer.toString(a);
anxietyouttw.setText(tempo);
break;
}
}
}
XML LAYOUT FILE
<?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">
<TextView
android:id="#+id/headertw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:layout_toEndOf="#+id/anxietyleveltw"
android:layout_toRightOf="#+id/anxietyleveltw"
android:text="#string/input_of_general_data_1_of_2"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold" />
<TextView
android:id="#+id/anxietyleveltw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/moodtw"
android:layout_alignStart="#+id/moodtw"
android:layout_below="#+id/moodtw"
android:layout_marginTop="15dp"
android:onClick="anxiety"
android:text="#string/anixiety"
android:textAppearance="#style/TextAppearance.AppCompat" />
<TextView
android:id="#+id/anxietyouttw"
android:layout_width="24dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/anxietyleveltw"
android:layout_alignBottom="#+id/anxietyleveltw"
android:layout_alignLeft="#+id/sleepouttw"
android:layout_alignStart="#+id/sleepouttw"
android:text="#string/_0"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textIsSelectable="false"
android:textSize="14sp" />
</RelativeLayout>
Set View as arg in method
public class Tab1 extends Fragment {
private View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab1, container, false);
return (rootView);
}
public void mood(View view) {
String tempo;
int a;
TextView moodouttw = (TextView) rootView.findViewById(R.id.moodouttw);
tempo = moodouttw.getText().toString();
a = Integer.parseInt(tempo);
if (a < 5) {
a = a + 1;
} else a = 0;
tempo = Integer.toString(a);
moodouttw.setText(tempo);
}
}
please try this
setOnClickListener for the textview for which you are setting OnClick in xml layout.
For eg
private View rootView;
private TextView textView;
In onCreateView
rootView = inflater.inflate(R.layout.tab1, container, false);
textView = rootView.findViewById(R.id.<your textview id>);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mood();
}
});
Related
Im working in a fragment where I want the user to input an answer and then when clicking a button, a textview should show Correct.
This is my code
public class FragmentOne extends Fragment {
private EditText userAnswer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
final String theAnswer = (userAnswer.getText().toString());
Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (theAnswer.equalsIgnoreCase("Germany")) {
TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
}
}
});
return v;
}
}
However, when Germany is typed, the textView is still just showing 'x' (which I set it to show originally)
Relevant XML's are
<Button
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:id="#+id/submitBtn1"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="220dp"
android:layout_height="70dp"
android:inputType="textPersonName"
android:hint="Write answer and press enter"
android:ems="10"
android:id="#+id/editText"
android:textSize="16sp"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true" />
<TextView
android:text="x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/showCorrect"
android:layout_below="#+id/skipBtn"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp" />
What has gone wrong?
You have to change this line :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
TextView tv = (TextView)v.findViewById(R.id.showCorrect);
Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
tv.setText("Correct!");
}
}
});
return v;
}
i.e : in your code userAnswer value is always the same (not checked on Button click)
Code needed to be changed to:
public class FragmentOne extends Fragment {
private EditText userAnswer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
final TextView tv = (TextView)v.findViewById(R.id.showCorrect); //changed
Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
//TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
}
// updateScore();
}
});
return v;
}
I Have a Fragment, and i want to add elements (textview, button) dynamically when i click on Floating Action Button.
Code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.xyz, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// new elements on click
// new elements on click
}
});
return view;
}
try this xml code for Fragment
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="10dp"
app:srcCompat="#android:drawable/ic_dialog_email"/>
</FrameLayout>
And java code for Fragment
package com.example.androiddeveloper.fragmentdynamic;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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 BlankFragment extends Fragment {
private LinearLayout linearLayout = null;
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_blank2, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
FloatingActionButton fab = (FloatingActionButton)view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Create your Controls(UI widget, Button,TextView) and add into layout
Button btn = new Button(getActivity());
btn.setText("Manual Add");
btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(btn);
}
});
}
}
You could do it like this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.xyz, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View view = YouFragmentClass.this.getView(); // returns base view of the fragment
if (view != null&&(view instanceof ViewGroup)){
//set the properties for button
Button btn = new Button(this);
btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btn.setText("Button");
ViewGroup viewGroup = (ViewGroup) view;
viewGroup.addView(btn);
}
}
});
return view;
}
I havent tested it but it should do the job
I am using ListView with ArrayAdapter and trying to add fragments to all rows of the ListView. However, the app does not work correctly: only one row on the screen showed with the added fragment but not all rows. Sometimes the app may be crashed because out of memory.
Can someone give me some advices? Thanks.
MainActivity.java
package com.me.test05;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
ListView myListView = (ListView) findViewById(R.id.myListView);
myListView.setAdapter(new MyArrayAdaptor(this, R.layout.row));
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
private static final String[] allnames = { "John", "Marry", "Smith", "Felicity", "Lion", "Math" };
public static class MyArrayAdaptor extends ArrayAdapter<String> {
private final Context context;
public MyArrayAdaptor(Context context, int resource) {
super(context, resource);
this.context = context;
}
#Override
public int getCount() {
return allnames.length * 100;
}
#Override
public String getItem(int position) {
return allnames[position % allnames.length];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
String str = getItem(position);
textView.setText(str);
FragmentTransaction ft = ((Activity) context).getFragmentManager().beginTransaction();
ft.replace(R.id.myFrameLayout, new PlaceholderFragment());
ft.commit();
return rowView;
}
}
}
File activity.xml:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:fitsSystemWindows="true">
<ListView android:id="#+id/myListView"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:dividerHeight="2px">
</ListView>
</merge>
File row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="abc" />
<FrameLayout
android:id="#+id/myFrameLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</FrameLayout>
</LinearLayout>
File fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="Button" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</LinearLayout>
Screen looks like:
I have solved that problem. The problem is the fragment manager always find (to replace by a new fragment) an id in global. That is why it always found and added all new fragments into the first row since it is the first one contains that id (as well as all other rows).
To solve the problem, I create dynamic ids which are unique for each row then replace that fixed id by them before letting fragment manager to do the rest. I also store those dynamic ids into rows' tags to reuse latter.
The new code is bellow, including the code for finding and reusing added fragments:
package com.me.test05;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
ListView myListView = (ListView) findViewById(R.id.myListView);
myListView.setAdapter(new MyArrayAdaptor(this, R.layout.row));
}
}
public static class PlaceholderFragment extends Fragment {
private View rootView = null;
private String theString = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
setString(theString);
return rootView;
}
public void setString(String str) {
theString = str;
if (theString != null && rootView != null) {
TextView textView = (TextView) rootView.findViewById(R.id.textView2);
textView.setText(str);
}
}
}
private static final String[] allnames = { "John", "Marry", "Smith", "Felicity", "Lion", "Math" };
public static class MyArrayAdaptor extends ArrayAdapter<String> {
private final Context context;
public MyArrayAdaptor(Context context, int resource) {
super(context, resource);
this.context = context;
}
#Override
public int getCount() {
return allnames.length * 100;
}
#Override
public String getItem(int position) {
return allnames[position % allnames.length];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;
PlaceholderFragment myFragment = null;
if (rowView == null) {
rowView = inflater.inflate(R.layout.row, parent, false);
int newId = 100000 + position;
FrameLayout layout = (FrameLayout) rowView.findViewById(R.id.myFrameLayout);
layout.setId(newId);
rowView.setTag(newId);
myFragment = new PlaceholderFragment();
FragmentTransaction ft = ((Activity) context).getFragmentManager().beginTransaction();
ft.replace(newId, myFragment, "" + newId).commit();
} else {
Integer theId = (Integer) convertView.getTag();
myFragment = (PlaceholderFragment) ((Activity) context).getFragmentManager().findFragmentById(theId);
}
String str = getItem(position);
myFragment.setString(str + ", " + position);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
textView.setText(str);
return rowView;
}
}
}
I am working on a simple app to convert the temperature. I am trying to figure out how to process a number that a user inputs and then process it and give out the conversion. I searched different places and found part of the following code but my app crashes when I actually click on the button.
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;
import android.widget.TextView;
import android.view.View.OnClickListener;
import org.w3c.dom.Text;
public class CelsiusFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.celsiusfragment, container, false);
Button celsiusbutton = (Button) view.findViewById(R.id.button_celsius);
celsiusbutton.setOnClickListener(this);
return view;
}
Button mButton;
EditText mEdit;
TextView mText;
int output;
#Override
public void onClick(View view) {
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int number = 0;
int number1 = number;
output = number1 + 2;
TextView result = (TextView) view.findViewById(R.id.result);
result.setText(String.valueOf(output));
}
});
}
}
Is there a tutorial that you would recommend to accomplish this?
Thanks!
Try to change your code like this:
fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_gravity="center_horizontal" />
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/calculate_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calculate"
android:layout_gravity="center_horizontal" />
</LinearLayout>
CelsiusFragment.java
public class CelsiusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
Button calculateButton = (Button) view.findViewById(R.id.calculate_button);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView result = (TextView) view.findViewById(R.id.result);
EditText value = (EditText) view.findViewById(R.id.value);
int output = Integer.parseInt(value.getText().toString()) + 2;
result.setText(String.valueOf(output));
}
});
return view;
}
}
I am very new to this.
How do I click a text and get it to open up an image which is saved in the app?
This is what I have so far, but I am having errors, I am using Fragments and I do not know if I am doing it the right way.
Thanks!
This is what I have now in Fragment_6.java :
package com.rufflez.swipeytabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_6 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_6, container, false);
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://androidcookbook.com/seam/resource/graphicImage/escapedn.png";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
}
in fragment_6.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="left"
android:clickable="true"
android:text="#string/procedures1"
/>
Change to
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v =inflater.inflate(R.layout.fragment_6, container, false);
// inflate the layout
TextView tv = (TextView) v.findViewById(R.id.textView1);
// initialize textview using inflated view object
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://androidcookbook.com/seam/resource/graphicImage/escapedn.png";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
reuturn v; // return view
}