Skip to main content

Fragmentation In Android

See more basics on Android along with interview questions

Fragments are a portion of an Activity:
Load a fragment Activity to call a fragment :
public class MainActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }  }
activity_main :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"> 
    <fragment
       android:id="@+id/titles"
       android:layout_width="0px"
       android:layout_height="match_parent"
       android:layout_weight="1"
      class="com.example.googlefragment.TitlesFragment"/>  
                               //calls the fragment
</LinearLayout> 
TitlesFragment :
public class TitlesFragment extends android.support.v4.app.ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;
    String titles[] = { "Item one", "Item two", "Item three" };
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      // Populate list with our static array of titles.setListAdapter(new ArrayAdapter(getActivity(), 
                                                    android.R.layout.simple_dropdown_item_1line,titles));

     // Check to see if we have a frame in which to embed the details
    // fragment directly in the containing UI.
      View detailsFrame = getActivity().findViewById(R.id.details);
      mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
      if (savedInstanceState != null) {
        // Restore last state for checked position.
         mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        } 
        if (mDualPane) { 
        // In dual-pane mode, the list view highlights  the selected item.
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        // Make sure our UI is in the correct state.
           showDetails(mCurCheckPosition);
         }else
         {
            System.out.println("NOT DUAL");
         }    } 

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }
    @Override
    public void onListItemClick(ListView l, View v,int position,long id) {
        showDetails(position);
    }
    void showDetails(int index) {
      mCurCheckPosition = index;
      if (mDualPane) {
      // We can display everything in-place with fragments,so update
      // the list to highlight the selected item and show the data.
      getListView().setItemChecked(index, true);
      // Check what fragment is currently shown,replace if needed.
      DetailsFragment details = (DetailsFragment)   
                                             getFragmentManager().findFragmentById(R.id.details);
      if (details == null || details.getShownIndex()!=index) {
      // Make new fragment to show this selection.
      details = DetailsFragment.newInstance(index);
      // Execute a transaction, replacing any existing fragment
      // with this one inside the frame.
      FragmentTransaction ft = getFragmentManager().beginTransaction();
      ft.replace(R.id.details, details);                        
      ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
      ft.commit();
      }
      } else {
      // Otherwise we need to launch a new activity to display
      // the dialog fragment with selected text.
      Intent intent = new Intent();
      intent.setClass(getActivity(),DetailsActivity.class);
      intent.putExtra("index", index);
      startActivity(intent);
        }    }}
                                                                           
DetailsActivity :
public class DetailsActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setContentView(R.layout.details_lay);
            System.out.println("LANNNNNNNNNNN");
            return;
        }
        if (savedInstanceState == null) {
            System.out.println("LLLLLLLLLLL");
            Fragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                                    .add(android.R.id.content, details).commit();

        }    } }
details_lay:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"> 
    <LinearLayout
        android:id="@+id/details"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.example.googlefragment.DetailsFragment"/> 
</LinearLayout> 
DetailsFragment :
public class DetailsFragment extends Fragment {
    static int i = 0;
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();
        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        i = index;
        f.setArguments(args);
        return f;
    }
    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
        if (container == null) {
            return null;
        }
        WebView wv = new WebView(getActivity());
        wv.loadData("Hello " + i, "text/html", "utf-8");
        return wv;
    } }
NOTE: Put layout under two separate folder for layout and portrait.

Comments

Popular posts from this blog

Spannable String in Android - URL Span ,Clickable Span, Rich-Style Formatting of Textview .....

See more Android Tutorials here....... Faster Loading images in GridViews or ListViews Spannable brings lots of possibility to TextView, includes displaying various appearance of a Text and onClick callbak. The SpannableString class allows you to easily format certain pieces which are called spans of a string, by applying CharacterStyle ie,color, font, ormake it a link . Here is an example where, explained how to use spannable string to give font size, color, linking a text via clickable span and through URL Span and to strike through the text. Lets go through the example : import android.os.Bundle; import android.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; import android.text.style.StrikethroughSpan; import android.text.style.URLSpan; import android.view.View; import android.widget.TextView; import android.widget.Toast;

Passing Images between Activities in Android

in First Activity: Intent intent=new Intent(FirstClass.this, SecondClass.class); Bundle bundle=new Bundle(); bundle.putInt("image",R.drawable.ic_launcher); intent.putExtras(bundle); startActivity(intent); in Second Acticity: Bundle bundle=this.getIntent().getExtras(); int pic=bundle.getInt("image"); v.setImageResource(pic); another method: in First Activity: Drawable drawable=imgv.getDrawable(); Bitmap bitmap= ((BitmapDrawable)drawable).getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] b = baos.toByteArray(); Intent intent=new Intent(Passimage.this,myclass.class); intent.putExtra("picture", b); startActivity(intent); in Second Acticity: Bundle extras = getIntent().getExtras(); byte[] b = extras.getByteArray("picture"); Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.lengt

Show and Resume Android Soft-Keyboard

Code to show keyboard: InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(yourEditText,InputMethodManager.SHOW_IMPLICIT); Code resume keyboard : InputMethodManager imm = (InputMethodManager)gettSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);