Demo:
1) MainActivity:
package
com.venky.fragmentdemo2;
import
android.annotation.SuppressLint;
import
android.app.Activity;
import
android.app.FragmentTransaction;
import
android.os.Bundle;
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction
fragmentTransaction = getFragmentManager()
.beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment, myFragment);
fragmentTransaction.commit();
}
}
2) MyFragement.java:
package
com.venky.fragmentdemo2;
import
android.annotation.SuppressLint;
import
android.app.Fragment;
import
android.os.Bundle;
import
android.view.LayoutInflater;
import
android.view.View;
import
android.view.ViewGroup;
@SuppressLint("NewApi")
public class MyFragment extends Fragment {
@Override
public View
onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO
Auto-generated method stub
View view =
inflater.inflate(R.layout.fragment_style, container, false);
return view;
}
}
3) main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:text="Fragment Demo
2"
android:textSize="25dp"
/>
<FrameLayout
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
</LinearLayout>
4) fragment_style.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:background="#5F04B4"
android:orientation="vertical"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Fragment"
android:textColor="#ffffff"
android:textSize="25dp"
/>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/one"
/>
</LinearLayout>
5)Download this Project Click Here
No comments:
Post a Comment