android when checkbox is checked show fragment - android

I am fresh at android programming and in my simple program,
I am trying to show fragment when CheckBox is checked and remove
fragment when CheckBox is not checked.
In my code, when I checked the CheckBox, fragment is shown and when I disable the CheckBox fragment is removed. However when I try to show it again I can not succeed it.
this is my part of code about checkbox
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(checkBox.isChecked())
{
checkBox.setText("It is on.");
MyFragment fragment = (MyFragment)getFragmentManager().findFragmentById(R.id.container);
if (fragment == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new MyFragment()).
commit();
}
}
else
{
checkBox.setText("It is off.");
MyFragment fragment = (MyFragment)getFragmentManager().findFragmentById(R.id.container);
if (fragment != null)
{
getFragmentManager().beginTransaction()
.remove(fragment)
.commit();
}
}
}
});
is there anybody can help me?

You cannot probably add it because you removed it completely, try to detatch it. By detaching it Fragment keeps its state.
try this:
getFragmentManager().beginTransaction()
.detach(fragment)
.commit();
}
Remove means the fragment instance cannot be re-attached. You will have to add it again to the fragment transaction.

try like this,
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
MyFragment fragment = (MyFragment)getFragmentManager().findFragmentById(R.id.container);
if(checkBox.isChecked())
{
checkBox.setText("It is on.");
getFragmentManager().beginTransaction()
.add(R.id.container, fragment).
commit();
}
else
{
checkBox.setText("It is off.");
if (fragment != null)
{
getFragmentManager().beginTransaction()
.remove(fragment)
.commit();
}
}
}
});

try it like this:
1)Create a layout for the fragment
<?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"
android:background="#ff0000">
</LinearLayout>
2)Create your fragment class which extends Fragment
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.myfragment, container,false);
}
}
3) In activity_main.xml put an empty layout with id
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/frag">
</LinearLayout>
</LinearLayout>
4)In MainActivity.java, Create an object of your Fragment class then add and remove it with FragmentManager
public class MainActivity extends Activity {
CheckBox cbox;
FragmentManager manager;
MyFragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = (FragmentManager) getFragmentManager();
frag = new MyFragment();
cbox = (CheckBox) findViewById(R.id.checkBox1);
cbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked==true){
manager.beginTransaction().add(R.id.frag, frag).commit();
}
else{
manager.beginTransaction().remove(frag).commit();
}
}
});
}
}

Related

Get edittext value from fragment

I am using fragments,I have an edittext in fragment and I want to get value in main activity.
This is my fragment layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#878787" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="dfgdfgdf"
android:textSize="20dp"
android:layout_centerInParent="true"
android:id="#+id/user_name"/>
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:text="Gönder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="getFromUser"
android:layout_marginTop="40dp"
/>
</RelativeLayout>
I am loading fragment with this function:
public void startChat(JsonObject user) {
FrameLayout layout = (FrameLayout)findViewById(R.id.container);
layout.setVisibility(View.VISIBLE);
Bundle bundle = new Bundle();
bundle.putString("name", user.get("name").getAsString());
sendTo=user.get("username").getAsString();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ConversationFragment conv = new ConversationFragment();
conv.setArguments(bundle);
fragmentTransaction.add(R.id.container, conv);
fragmentTransaction.commit();
viewPager.setVisibility(View.GONE);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayHomeAsUpEnabled(true);
}
And this is my fragment class
public class ConversationFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String name = getArguments().getString("name");
View rootView = inflater.inflate(R.layout.fragment_conversation, container, false);
TextView username=(TextView)rootView.findViewById(R.id.user_name);
username.setText(name);
return rootView;
}
}
As you can see when press the button main activity runs "getFromUser" function.I want to get edittext value in this function.How can I do this ?
It's always the same procedure for these things. You can't access a fragment's views just like that. You need a callback method.
Add this code to ConversationFragment:
private OnGetFromUserClickListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnGetFromUserClickListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnGetFromUserClickListener");
}
}
public void getFromUser(View v) {
if (mListener != null) {
EditText edit = (EditText)findViewById(R.id.message);
mListener.getFromUser(edit.getText().toString());
}
}
public interface OnGetFromUserClickListener {
void getFromUser(String message);
}
Make your MainActivity implement this interface. Replace getFromUser() inside MainActivity with:
public void getFromUser(String message) {
sendMessage(message);
}
Done.
Edit:
Actually, using the XML-onClick attribute is currently bugged (see onClick inside fragment called on Activity): It links to the activity instead of the fragment. You have to set the click listener programmatically to make sure the code won't break at some point in the future. So give the button an ID inside the XML (e.g. get_from_user) and add this code to onCreateView inside ConversationFragment:
v.findViewById(R.id.get_from_user).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.get_from_user) {
getFromUser(v);
}
}
});
Using this code vastly decouples the activity and the fragment from each other.
I resolved this problem.
public void getFromUser(View view) {
ConversationFragment fragment1 = (ConversationFragment)getSupportFragmentManager().findFragmentById(R.id.container);
View frag=fragment1.getView();
EditText editText1 =(EditText) frag.findViewById(R.id.message);
String message=editText1.getText().toString();
sendMessage(message);
}
Now I can get edittext value from fragment.

Change Fragment dynamic

I have 2 questions. First, can me say someone, why this not works? I just try to change the fragment, but he does nothing. I just see the first fragment.
mainActivity:
...
if (savedInstanceState == null) {
fm.beginTransaction()
.add(R.id.firstFragment, new firstFragment()).commit();
}
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switchFragment(R.id.firstFragment, new firstFragment());
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switchFragment(R.id.secondFragment, new secondFragment());
}
});
}
private void switchFragment(int fragId, Fragment frag){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(fragId, frag);
ft.commit();
}
Fragments like this in the main.xml:
<Fragment
android:id="#+id/firstFragment"
android:name="com.example.firstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/View01"
android:layout_below="#+id/view1" />
Fragmentclass just have this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_clublist, container, false);
return view;
}
And a Fragment just look like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFF0000"/>
I don't know, why he does not change the fragment. A check, that switchFragment really calling is true.
Second question is: Is this a good way to change fragments? What is, if i have 10 fragments?
Thanks for your help! :)
int fragId
should be the id of the container that hosts the Fragment, not the id of the fragment itself

Trying to learn fragments, why fragment is not showing up

Here is the xml for my main layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_placeholder"
android:layout_width="250dp"
android:layout_height="0dip"
android:layout_weight="1" >
<ImageView
android:contentDescription="image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</FrameLayout>
</LinearLayout>
Code for fragment class
public class ExerciseFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_layout, container, false);
return view;
}
}
and code in main activity for showing fragment on click of a button:
ExerciseFragment fragment = new ExerciseFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_placeholder, fragment);
ft.commit();
if (fragment.isVisible()) {
Toast.makeText(this, "works", Toast.LENGTH_LONG).show();
} else
Toast.makeText(this, "nooooo", Toast.LENGTH_LONG).show();
The toast says "noooo" meaning the fragment is not visible, and it still shows an image which i set up in the framelayout holder which i want to replace. Any ideas why the fragment is not showing up?
EDIT: COMPLETE CODE FOR MAIN ACTIVITY
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayHomeAsUpEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.workout_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_exercise:
ExerciseFragment fragment = new ExerciseFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_placeholder, fragment);
ft.commit();
if (fragment.isVisible()) {
Toast.makeText(this, "works", Toast.LENGTH_LONG).show();
} else
Toast.makeText(this, "nooooo", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
}
Instead of using ft.replace(R.id.fragment_placeholder, fragment);, try using ft.add(R.id.fragment_placeholder, fragment);. Since the R.id.fragment_placeholder doesn't contain a fragment yet, you aren't replacing anything, you are merely adding on to the layout. The .add(int containerViewId, Fragment fragment) function should work for your case. In the future, if you are going to change the fragment contained in R.id.fragment_placeholder, use .replace(int containerViewId, Fragment fragment).
Hope this works!

Accessing Views inside fragment

I'm having troubles accessing the Views that within my Fragment. In the example below, I can't access the 2nd button that is within the Fragment (e.g., findViewById appears to return NULL and the app crashes when I try b2.setText("test") ), but when I directly add it in the activity_main.xml, it does work.
Here is the code:
MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button fragmentButton = (Button)findViewById(R.id.iMainButton);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.iMainInnerLLContainer, new TestFragment());
ft.commit();
final Button b2 = (Button)findViewById(R.id.iTestFragmentInnerButton);
if(b2 == null) { Log.d("MainActivity.java:", "b2 is null"); }
else { Log.d("MainActivity.java:", "b2 is NOT null"); }
fragmentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// do stuff here
}
});
}
}
activity_main.xml
<LinearLayout 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:id="#+id/iMainRootLinearLayoutContainer"
android:orientation="vertical"
>
<Button
android:id="#+id/iMainButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Add fragment..."
/>
<LinearLayout
android:id="#+id/iMainInnerLLContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
>
<!-- Fragment goes here, can reference button if it is added here manually -->
</LinearLayout>
</LinearLayout>
TestFragment.java
public class TestFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.ltestfragment, container, false);
}
}
ltestfragment.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"
android:id="#+id/iTestFragmentOuterLinearLayout"
>
<Button
android:id="#+id/iTestFragmentInnerButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="This is my test fragment button."
/>
</LinearLayout>
I think I'm missing something very basic here and I would appreciate some insight on what that might be.
Thank you in advance!
I think you need to set up a textchangelistener in your fragment.
public class FragmentA extends Fragment {
TextChangeListener listener;
public interface TextChangeListener {
public void onTextChange(CharSequence newText);
}
public void setTextChangeListener(TextChangeListener listener) {
this.listener = listener;
}
Then, in your activity, set up the listener :
public class ActivityAB extends FragmentActivity {
FragmentA fragmentA;
FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ab);
FragmentManager manager = getSupportFragmentManager();
fragmentA = (FragmentA) manager.findFragmentById(R.id.fragmentA);
fragmentB = (FragmentB) manager.findFragmentById(R.id.fragmentB);
fragmentA.setTextChangeListener(new TextChangeListener() {
#Override
public void onTextChange(CharSequence newText) {
fragmentB.updateTextValue(newText);
}
});
}
}
Implement an interface to listen to the events of a fragment from its activity.
Code in Fragment:-
public class TestFragment extends Fragment
{
public interface OnClickListener
{
public void onButtonClicked(<data type><data>);
}
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listener.onButtonClicked(<<pass some values here>>);
}
});
}
Code in Main:-
MainActivity extends FragmentActivity implements TestFragment.OnClickListener,
{
#Override
public void onButtonClicked(<<receive the pased data here>>) {
//do some stuff here with the received data after the button is clicked
}
}

how to set up ListFragment properly?

I try to create tabs with ListFragment in it. I've tried several different appoaches but neither of them works. I don't know how to set container for ListFragment obkect properly.
Here is java code.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabOne = actionBar.newTab().setText("ONE");
ActionBar.Tab tabTwo = actionBar.newTab().setText("TWO");
tabParkCinema.setTabListener(new tabListener());
tab28Cinema.setTabListener(new tabListener());
actionBar.addTab(tabOne);
actionBar.addTab(tabTwo);
}
protected class tabListener implements ActionBar.TabListener {
ParkFragment firstFragment;
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()){
case 0:
if (firstFragment == null){
firstFragment = new ParkFragment();
System.out.println("initialized");
ft.add(R.id.cont, firstFragment,"FIRST");
}
else{
ft.attach(firstFragment);
}
break;
case 1:
if (firstFragment == null){
firstFragment = new ParkFragment();
ft.add(R.id.cont,firstFragment,"SECOND");
}
else{
ft.attach(firstFragment);
}
break;
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
};
public class ParkFragment extends ListFragment {
private ArrayList<Cinemas> cinema;
private CinemasAdapter cinemaAdapter;
private View v;
//private ListView list;
#Override
public View onCreateView(LayoutInflater in, ViewGroup gr, Bundle savedInstanceState) {
v = in.inflate(R.id.listing1, gr,false);
super.onActivityCreated(savedInstanceState);
cinema = new Handler().handle();
cinemaAdapter = new CinemasAdapter(MainActivity.this, R.layout.movie_data_row, cinema);
setListAdapter(cinemaAdapter);
return gr;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Cinemas movie = cinemaAdapter.getItem(position);
Intent intent = new Intent (MainActivity.this, More.class);
intent.putExtra("Cinemas", movie);
intent.putExtra("data", movie.getBitmap());
Bundle translateBundle =
ActivityOptions.makeCustomAnimation(MainActivity.this,
R.anim.slide_in_left, R.anim.slide_out_left).toBundle();
startActivity (intent, translateBundle);
}
}
}
And activity_main.XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cont"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id = "#+id/listing1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
Thank you for reading, any help will be appreciated!
1) Create a FragmentManager object.
2) Use method beginTransaction() on this object to create a FragmentTransaction object.
3) Add fragment with the method add(int containerViewId, Fragment fragment, String tag) on the FragmentTransaction object.
In this method, you put a reference to the id of the container, a new ListFragment (or the class you have writen) and a tag (to easily get a reference to the ListFragment if needed).
Note that you have to change your xml layout. You can add a FrameLayout with an id. And then, give this id to the method add() of your FragmentTransaction object.
EDIT
Example of code:
public class ContentActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
//your action bar stuff
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.parkfragment, new ParkFragment(), "locations");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
}
public class ParkFragment extends ListFragment {
//your methods
}
protected class tabListener implements ActionBar.TabListener {
//your methods
}
}
Your xml would look like:
<?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:baselineAligned="false"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/parkfragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

Categories

Resources