Search code examples
androidandroid-layoutandroid-fragmentsandroid-listfragmentoncreate

onCreateView() and onActivityCreated() in MyAddFragment class invokes a lot more than required by working with dynamic fragment


I am new at android app development.I have a problem with my app.I am doing a simple 'Todo List App'. When I deploy my app to android phone.First time it works well.When I change orientation of device, onCreateView() and onActivityCreated() in MyAddFragment works multiple.And 'Add Button' doesn't work after changing orientation.****Please help me how to get rid of the problem.

The following my activity and fragment classes and xml files.

public class MainActivity extends Activity implements Communicator{
FragmentManager man;
private ArrayAdapter<String> todoArrayAdapter;
private ArrayList<String> todoItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    man = getFragmentManager();
    MyAddFragment f1 = new MyAddFragment();
    MyListFragment f2 = new MyListFragment();


    FragmentTransaction transaction = man.beginTransaction();
    transaction.add(R.id.frameLayout1, f1, "Add");
    transaction.add(R.id.frameLayout2, f2,"List");


    Log.i("a", "onCreate - ADDED FRAGMENT");
    if (savedInstanceState == null) {
        todoItems = new ArrayList<String>();

    }else {
        todoItems = savedInstanceState.getStringArrayList("veri");
    }

    todoArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);
    f2.setListAdapter(todoArrayAdapter);
    transaction.commit();

}

public void respond(String data) {
    MyListFragment fb = (MyListFragment) man.findFragmentById(R.id.frameLayout2);
    todoItems.add(data);
    todoArrayAdapter.notifyDataSetChanged();
}

@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);
}
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArrayList("veri", todoItems);
}

}

public class MyAddFragment extends Fragment{
Button btnAdd;
EditText txtEdit;
Communicator comm;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_add, container,false);

    return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
    txtEdit = (EditText) getActivity().findViewById(R.id.txtEdit);
    comm = (Communicator) getActivity();
    btnAdd.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String newRecord = txtEdit.getText().toString();
            comm.respond(newRecord);
            txtEdit.setText("");
        }
    });
}

}

public class MyListFragment extends ListFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list, container,false);

    return view;
}

}

public interface Communicator {
public void respond(String data);

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
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.ceng389hw1.MainActivity" >

<FrameLayout
    android:id="@+id/frameLayout1"
    android:layout_width="fill_parent"
    android:layout_height="40dp"
    android:layout_alignParentLeft="true"
    android:background="#ab3e0f" >

</FrameLayout>

<FrameLayout
    android:id="@+id/frameLayout2"
    android:layout_width="fill_parent"
    android:layout_height="20dp"
    android:layout_alignParentBottom="true"
    android:layout_below="@+id/frameLayout1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"
    android:background="#ab3eab"
   >

</FrameLayout>
</RelativeLayout>

fragment_add.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" 
android:background="#ab3e0f">

 <Button
    android:id="@+id/btnAdd"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="@string/btnStringAdd" />

<EditText
    android:id="@+id/txtEdit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/btnAdd"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@+id/btnAdd"
    android:ems="10"
    android:inputType="text" />

</RelativeLayout>

fragment_list.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:background="#ab5810" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

Solution

  • You should change two files in your Application.

    First step, you should add following code in androidmanifest file.

    android:configChanges="orientation|screenSize"
    

    After you add the code to Androidmanifest, Your androidmanifes file must be like below.

    <activity
                android:name="com.example.ceng389hw1.MainActivity"
                android:configChanges="orientation|screenSize"
                android:label="@string/app_name" >
    

    Secon Step, You must be override onConfigurationChanged function like below.

    @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
    
            // Checks the orientation of the screen
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Toast.makeText( this, "landscape", Toast.LENGTH_SHORT ).show();
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
                Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
            }
        }
    

    For more detail -> http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange