How to open new activity when ImageView is click in the fragment - android

Hi Im a newbie in android, can some help me implement a click on my ImageView to open new activity. I tried several codes but the app crashes on launch. Here is my code on fragments
Fragment1.xml
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:fontFamily="sans-serif-light"
android:paddingBottom="15dp"
android:paddingTop="8dp" >
<ImageView
android:id="#+id/selectone"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:background="#drawable/fashion"
android:clickable="true"
android:focusable="true"
android:onClick="onClick"
android:scaleType="centerCrop" />
<ImageView
android:id="#+id/selecttwo"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_below="#+id/selectone"
android:layout_marginTop="8dp"
android:background="#drawable/lingerie"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/titlelabel1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/selectone"
android:background="#80000000"
android:fontFamily="sans-serif-light"
android:padding="10dp"
android:text="Fashion"
android:textColor="#fefefe"
android:textSize="28sp"
android:textStyle="italic" />
<TextView
android:id="#+id/titlelabel2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/selecttwo"
android:background="#80000000"
android:fontFamily="sans-serif-light"
android:padding="10dp"
android:text="Lingerie"
android:textColor="#fefefe"
android:textSize="28sp"
android:textStyle="italic" />
</RelativeLayout>
Fragment1.java
package com.androidbegin.sidemenututorial;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment1 extends SherlockFragment {
ImageView fashionImg;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get the button view
fashionImg = (ImageView) getView().findViewById(R.id.selectone);
//set a onclick listener for when the button gets clicked
fashionImg.setOnClickListener(new OnClickListener() {
//Start new list activity
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(), CarouselActivity.class);
startActivity(mainIntent);
}
});
}
}

As shown below add code into onActivityCreated() instead of onCreate()
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// get the button view
fashionImg = (ImageView) getView().findViewById(R.id.selectone);
// set a onclick listener for when the button gets clicked
fashionImg.setOnClickListener(new OnClickListener() {
// Start new list activity
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(),
CarouselActivity.class);
startActivity(mainIntent);
}
});
}

try getApplicationContext() instead of getActivity()

You need to write your Fragment1 class like this :
public class Fragment1 extends SherlockFragment {
ImageView fashionImg;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
//get the button view
fashionImg = (ImageView) getView().findViewById(R.id.selectone);
return rootView;
}
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(), CarouselActivity.class);
startActivity(mainIntent);
}
}

You should change this by:
fashionImg = (ImageView) getView().findViewById(R.id.selectone);
to
fashionImg = (ImageView) getActivity().findViewById(R.id.selectone);

First, replace android:onClick="onClick" in the ImageView with something like android:onClick="onClickTest". Then in the code write something like:
public void onClickTest(View v){
//The MainActivity being the starting point
Intent int = new Intent(MainActivity.this,
CarouselActivity.class);
MainActivity.this.startActivity(mainIntent);
}

add the listener in onCreateView. Refer Fragment lifecycle, the problem is onCreate is called before onCreateView so your fragment's view is not added to the parent container view by that time.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
//get the button view
fashionImg = (ImageView) rootView.findViewById(R.id.selectone);
//set a onclick listener for when the button gets clicked
fashionImg.setOnClickListener(new OnClickListener() {
//Start new list activity
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(), CarouselActivity.class);
startActivity(mainIntent);
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

Try the following, first place an ImageView like this
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>
Then place all other ImageView or images over this.
In your 'Fragment1' class use OnTouchListener.
image1 = (ImageView) findViewById(R.id.imageView1);
image1.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Intent mainIntent =new Intent(Fragment1.this,CarouselActivity.class);
stratActivity(mainIntent);
return true;
}
});

Related

How to add intent for imageview in fragment page?

i want to add an intent for an imageview onclick which links to a weburl. below u can see the xml file of home fragment page and java file of home fragment.kindly help me with this
HomeFragment.xml
<ImageView
android:id="#+id/imageView2"
android:layout_width="80dp"
android:layout_height="25dp"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/imageView1"
android:layout_marginRight="15dp"
android:src="#drawable/scial" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="130dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="11dp"
android:src="#drawable/log" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView1"
android:src="#drawable/line" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="180dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView3"
android:src="#drawable/banner" />
<ImageView
android:id="#+id/imageView5"
android:layout_width="400dp"
android:layout_height="300dp"
android:layout_below="#+id/imageView4"
android:layout_centerHorizontal="true"
android:src="#drawable/mainn" />
</RelativeLayout>
HomeFragment.java
package com.tabs;
import com.tabs.R;
import android.os.Bundle;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
Add a intent to one of the imageview's with the required address of webpage. Try this:
image.setOnClickListener(new View.onClickListener(){
String url = "http://www.google.com";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(i);
});
Have you tried adding inside your onCreateView?
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.your_weburl.com";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(i);
}
});
You should use image button; i.e: ib_playPause
XML
ImageButton
android:id="#+id/ib_play"
android:src="#drawable/ic_play"
JAVA:
private ImageButton play;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
play = (ImageButton) rootView .findViewById(R.id.ib_play);
return rootView;
}
//for onclick
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Uri uri = Uri
.parse("https://play.google.com/store");
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
}

Button onclick inside fragment is not working

I am trying to set / override the onclick method for a button (R.id.buy_button) inside one of my views (inside a fragment). The application doesn't return errors. However it does not trigger the onclick method. I'm not sure if my implementation is wrong or perhaps my button is incorrectly configured. Any help / comments / guidance would be appreciated.
My onCreateView is here:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_item, container, false);
Button b = (Button) view.findViewById(R.id.buy_button);
b.setOnClickListener(this);
return inflater.inflate(R.layout.fragment_item_list, container, false);
}
My entire fragment code:
public static class AlbumsFragment extends ListFragment implements View.OnClickListener {
private static final String ARG_SECTION_NUMBER = "section_number";
public AlbumsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle b){
super.onActivityCreated(b);
ListView listView = getListView();
List<Album> albums = null;
albums = Album.listAll(Album.class);
Log.i("ALBUMS", albums.toString());
ArrayAdapter<Album> adapter =
new ArrayAdapter<Album>(getActivity(), R.layout.list_item, R.id.textView, albums);
if (!albums.equals("")) {
listView.setAdapter(adapter);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_item, container, false);
Button b = (Button) view.findViewById(R.id.buy_button);
b.setOnClickListener(this);
return inflater.inflate(R.layout.fragment_item_list, container, false);
}
public void gotoPurchaseWeb() {
Context context = getActivity().getApplicationContext();
Intent intent = new Intent(context, PurchaseSong.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static AlbumsFragment newInstance(int sectionNumber) {
AlbumsFragment fragment = new AlbumsFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buy_button:
Context context = getActivity().getApplicationContext();
Intent intent = new Intent(context, PurchaseSong.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
break;
}
}
}
My list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left sied Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:weightSum="1"
android:showDividers="middle|end"
android:visibility="visible">
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/black"/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textView"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_marginTop="#dimen/zero_space"
android:layout_marginBottom="#dimen/zero_space"
android:paddingTop="3dp"
android:paddingLeft="8dp"
android:paddingRight="5dp"
android:paddingBottom="0dp"
android:layout_weight="24.33" />
</LinearLayout>
<Button
style="#style/ButtonText"
android:layout_width="wrap_content"
android:layout_height="#dimen/button_height"
android:text="#string/buy_album"
android:id="#+id/buy_button"
android:background="#drawable/blue_button"
android:paddingTop="7dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp" />
My entire project:
https://github.com/markbratanov/MyFitPlayer/tree/master/Player/src/main/java/com/markbratanov/myfitplayer
Any help would be appreciated. Thanks.
You should return your View instead of returning new inflated instance of your View in onCreateView callback function inside of your Fragment.
return inflater.inflate(R.layout.fragment_item_list, container, false);
instead use :
return view;
do this in onCreateView view method u need to inflate fragment like this for button click
View view = inflater.inflate(R.layout.fragment_blank3,
container, false);
Button bt1=(Button)view.findViewbyId(R.id.buttton);
bt1.setOnclick...
//then return in on create view.
return view;
I had the same problem. My button onclick listener was not working inside the fragment.
Try this: add the android:onclick="" inside the button XML before the closing TAG and create a class inside the mainActivity.java file having the same name as the class name you declared inside the XML. Then do whatever you want to do in the onclick event. Write it inside the class you created recently for the click event.

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
}

How to inflate view inside fragment

If I try to inflate a view within a fragment I am getting NULL.. For example:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Here I will inflate my view using the layout ID & return.
return view;
}
Whenever a button is clicked I need to create a dynamic view e.g.: button & add to the LinearLayout. I would like to perform this operation inside my fragment class like this:
public void addPlaces() {
Button button = new Button(null);
button.setText("button name");
// e.g. like adding button to enter code here linear layout
linearLayout.addView(button);
}
So, if I get inflate LinearLayout inside onCreateView and use it in add class, I'm getting NULL. How to achieve?
Declare the variable as a instance variable and then initialize Linear Layout
LinearLayout linearLayout;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
return rootView;
}
Then
public void addPlaces() {
Button button = new Button(getActivity());
// needs activity context
// fragment hosted by a activity. use getActivity() to get the context of the hosting activity.
button.setText("button name");
linearlayout.addView(button);
}
Example: Modify the below according to your requirement.
fragment1.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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<LinearLayout
android:layout_width="fill_parent"
android:id="#+id/linearlayout"
android:layout_height="fill_parent"
android:layout_above="#+id/button1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
Myfragment.java
public class Myfragment extends Fragment {
LinearLayout linearLayout;
View rootView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPlaces();
}
});
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
public void addPlaces() {
Button button = new Button(getActivity()); // needs activity context
button.setText("button name");
linearLayout.addView(button);
}
}
Snap shot of my emulator
Edit :
activity-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=".MainActivity" >
<fragment android:name="com.example.fragments.Myfragment"
android:id="#+id/frag"
android:layout_above="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends FragmentActivity {
Button b;
Myfragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment = new Myfragment();
fragmentTransaction.add(R.id.frag, fragment);
fragmentTransaction.commit();
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fragment.addPlaces();
}
});
}
}
Myfragment.java
public class Myfragment extends Fragment {
LinearLayout linearLayout;
View rootView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
public void addPlaces() {
Button button = new Button(getActivity()); // needs activity context
button.setText("button name");
linearLayout.addView(button);
}
}

Categories

Resources