How to add elements dynamically in fragment in android - android

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

Related

How to make button on click listener in fragment

I want to set an onClickListener on a button, but I am facing a problem.
I can't get the context I need after the button is clicked.
I tried by view but didn't work, it doesn't work but also doesn't throw an error.
The xml file in fragment:
<?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">
<Button
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="go to test" />
</RelativeLayout>
Java fragment code :
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import java.util.Objects;
public class Homefragment extends android.support.v4.app.Fragment {
Button test;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
test = (Button) view.findViewById(R.id.test);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Clicked go to test");
Toast.makeText(getContext(), "clicked", Toast.LENGTH_SHORT).show();
Intent gotest;
gotest = new Intent(getActivity().getApplicationContext(),testing.class);
startActivity(gotest);
}
});
return inflater.inflate(R.layout.fragment_home,null);
}
}
My logcat gives no error and I use print command when the button is clicked but print does not work, like if the button is not clicked.
Use this return your view.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
test = (Button) view.findViewById(R.id.test);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Clicked go to test");
Toast.makeText(getContext(), "clicked", Toast.LENGTH_SHORT).show();
Intent gotest;
gotest = new Intent(getActivity().getApplicationContext(),testing.class);
startActivity(gotest);
}
});
return view;
}

Could not find method in a javaclass (extends Fragment)

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();
}
});

onClickListener is not working within onCreateView method

Im using the following code to create Floating Action button. Its within a relative layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/tools"
android:background="#drawable/form_bg">
<android.support.design.widget.FloatingActionButton
android:id="#+id/myFAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fab_bg_mini"
app:elevation="4dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/trans_white"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<WebView
android:id="#+id/chart"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Here is how Im setting the onClickListener for the floating action button within onCreateView method.
public class TrendChart extends Fragment {
private View mRootview;
private static final String URL = "file:///android_asset/taskstatus.html";
private WebView chart;
class InnerWebView extends WebViewClient {
InnerWebView() {
}
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript: loadTrendChart();");
}
}
public static final TrendChart newInstance(String company_name) {
TrendChart f = new TrendChart();
f.setArguments(new Bundle(1));
return f;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
mRootview = inflater.inflate(R.layout.trend_chart, null);
this.chart = (WebView) mRootview.findViewById(R.id.chart);
this.chart.getSettings().setJavaScriptEnabled(true);
this.chart.setWebChromeClient(new WebChromeClient());
this.chart.setWebViewClient(new InnerWebView());
refreshWebView();
return mRootview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FloatingActionButton myFab = (FloatingActionButton) getActivity().findViewById(R.id.myFAB);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("Clicked","Hello");
}
});
}
private void refreshWebView() {
this.chart.loadUrl(URL);
}
}
The problem is that onClickListener is not getting fired. Why is that so? I tried putting listener within onCreateView method too but still the problem persists. Is there any ways through which I can use floating button within a class that extends Fragments?
You have to put your code when the Activity is fully created as follows :
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
FloatingActionButton myFab = (FloatingActionButton) getActivity().findViewById(R.id.myFAB);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("Check","Clicked");
}
});
}
If you have your code on onCreateView() your code should look like this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.YOUR_LAYOUT, container, false);
FloatingActionButton myFab = (FloatingActionButton) view.findViewById(R.id.myFAB);
myFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do stuff
}
});
return view;
}
EDIT
Change this :
mRootview = inflater.inflate(R.layout.trend_chart, null);
to this :
mRootview = inflater.inflate(R.layout.trend_chart, container, false);

Android EditText giving error on onclick method

I am trying to read in contents of w_number_edit_text(a textbox) after the login(a button) is clicked. But on the OnClick method I can't seem to access the contents of w_number_edit_text. Both the textbox and the button is on the fragment xml instead of main.xml. Can anyone tell me how to fix this problem. In short how do I access contents of EditText after the Button is clicked? Thank You
My code is below:
package com.example.medrec;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements OnClickListener{
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button login = (Button)rootView.findViewById(R.id.w_login);
login.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
//////////////////////////// Problem is here
EditText wNumbers =(EditText)findViewById(R.id.w_number_edit_text);
String wNumber = wNumbers.getText().toString();
Toast.makeText(getActivity(), wNumber, Toast.LENGTH_LONG).show();
}
}
}
My activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.medrec.MainActivity"
tools:ignore="MergeRootFrame" />
My fragment_main.xml
<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"
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.medrec.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/w_number_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="118dp"
android:text="#string/w_number" />
<Button
android:id="#+id/w_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/w_number_edit_text"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="#string/w_login_text" />
</RelativeLayout>
You should change this
EditText wNumbers =(EditText)findViewById(R.id.w_number_edit_text);
With
EditText wNumbers =(EditText)rootview.findViewById(R.id.w_number_edit_text);
and onCreateView(......) like a below:
EditText wNumbers
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button login = (Button)rootView.findViewById(R.id.w_login);
wNumbers =(EditText)rootView.findViewById(R.id.w_number_edit_text);
login.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String wNumber = wNumbers.getText().toString();
Toast.makeText(getActivity(), wNumber, Toast.LENGTH_LONG).show();
}
});
return rootView;
}
Try this..
You cannot use this inside Fragment you have to use getActivity()
View rootView ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button login = (Button)rootView.findViewById(R.id.w_login);
login.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText wNumbers =(EditText)rootView.findViewById(R.id.w_number_edit_text);
String wNumber = wNumbers.getText().toString();
Toast.makeText(getActivity(), wNumber, Toast.LENGTH_LONG).show();
}
});
return rootView;
}
Initialise EditText on onCreateView :-
public static class PlaceholderFragment extends Fragment implements OnClickListener{
public PlaceholderFragment()
{
}
EditText wNumbers
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
wNumbers =(EditText)rootView.findViewById(R.id.w_number_edit_text);
Button login = (Button)rootView.findViewById(R.id.w_login);
login.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String wNumber = wNumbers.getText().toString();
Toast.makeText(getActivity(), wNumber, Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
Define rootview in the class.
and detect your EditText using rootView.findviewbyid like below,
EditText wNumbers =(EditText)rootView.findViewById(R.id.w_number_edit_text);
And the onCreateView() code is as below,
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button login = (Button)rootView.findViewById(R.id.w_login);
login.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
//////////////////////////// Problem is here
EditText wNumbers =(EditText)rootView.findViewById(R.id.w_number_edit_text);
String wNumber = wNumbers.getText().toString();
Toast.makeText(getActivity(), wNumber, Toast.LENGTH_LONG).show();
}

Click on a text to open an image

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
}

Categories

Resources