I'm trying to create a navigation drawer in a fragment, but my app keeps crashing. The navigation drawer itself works fine without a drawer toggle. The problem is that when I try to add the code to create a drawer toggle, the app crashes. What am I doing wrong?
TestListFragment:
public class TestListFragment extends Fragment {
private RecyclerView testRecycler;
private String[] names;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test_list, container, false);
Toolbar toolbar = view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) view.findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(getActivity(), drawer, toolbar, R.string.nav_open_drawer, R.string.nav_close_drawer);
drawer.addDrawerListener(toggle);
toggle.syncState();
testRecycler = view.findViewById(R.id.test_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
testRecycler.setLayoutManager(layoutManager);
names = new String[Test.testData.length];
for(int i = 0; i < names.length; i++) {
names[i] = Test.testData[i].getTitle();
}
TestAdapter adapter = new TestAdapter(names);
testRecycler.setAdapter(adapter);
return view;
}
}
fragment_test_list:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/toolbar_main"
android:id="#+id/toolbar" />
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/test_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/menu_nav" />
</androidx.drawerlayout.widget.DrawerLayout>
toolbar_main:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
menu_nav:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/category1"
android:title="#string/category_1" />
<item
android:id="#+id/category2"
android:title="#string/category_2" />
</menu>
Related
I have a fragment which basically has a recyclerView. So when the user clicks on any item of the view, the background needs to change (the item clicked needs to be highlighted) and a loading spinner needs to appear and then fragment needs to replaced based on the item clicked. How to achieve this? In the below code, I have implemented the highlight facility, but once an item is clicked redirection should happen....
My Internal Layout, (layout_research)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="#dimen/loginCardRadius"
android:elevation="5dp"
android:layout_gravity="center"
android:layout_marginTop="#dimen/loginViewsMargin"
android:layout_marginBottom="#dimen/loginViewsMargin"
android:background="#ffffff">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:padding="#dimen/loginViewsMargin">
<ImageView
android:contentDescription="#string/abc"
android:src="#drawable/logo"
android:layout_gravity="center"
android:layout_height="100dp"
android:layout_width="wrap_content"
android:layout_marginTop="#dimen/loginViewsMargin"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/grid_view"
android:layout_marginTop="20dp"
tools:listitem="#layout/row_item"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
My External Layout,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ScrollView
android:fillViewport="true"
android:layout_height="match_parent"
android:layout_width="match_parent">
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:baselineAligned="true"
android:weightSum="12"
android:background="#drawable/login_shape_bk"
android:orientation="vertical"
android:layout_weight="3">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ic_login_bk" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:layout_marginTop="40dp"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textColor="#ffffff"
android:textSize="22sp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_gravity="center"
android:text="#string/abcd"/>
<include
layout="#layout/internal_research"/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
My Java File,
package com.example.a123;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class research extends Fragment {
int selectedPosition=-1;
private String[] names = {"Blogs & Books","Patents","Projects","Publications"};
private int[] image ={R.drawable.books,R.drawable.patents,R.drawable.project,R.drawable.publications};
private ArrayList<adapter_for_research> mProfiles;
private RecyclerView mProfileRecyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
mProfiles = new ArrayList<>();
for(int i =0;i<names.length;i++){
adapter_for_research s = new adapter_for_research();
s.setname(names[i]);
s.setImageId(image[i]);
mProfiles.add(s);
}
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_research, container, false);
mProfileRecyclerView = view.findViewById(R.id.grid_view);
updateUI();
return view;
}
private void updateUI(){
ProfileAdapter mAdapter = new ProfileAdapter(mProfiles);
mProfileRecyclerView.setAdapter(mAdapter);
}
private class ProfileHolder extends RecyclerView.ViewHolder {
private adapter_for_research mProfilecsg;
private ImageView mImageView;
private TextView mnameTextView;
private ProfileHolder(final View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image_view);
mnameTextView = itemView.findViewById(R.id.text_view);
}
private void bindData(adapter_for_research s){
mProfilecsg = s;
mImageView.setImageResource(s.getImageId());
mnameTextView.setText(s.getname());
}
}
private class ProfileAdapter extends RecyclerView.Adapter<ProfileHolder>{
private ArrayList<adapter_for_research> mProfiles;
private ProfileAdapter(ArrayList<adapter_for_research> profile){
mProfiles = profile;
}
#NonNull
public ProfileHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_item,parent,false);
return new ProfileHolder(view);
}
#Override
public void onBindViewHolder(ProfileHolder holder, final int position) {
adapter_for_research s = mProfiles.get(position);
holder.bindData(s);
if(selectedPosition==position)
holder.itemView.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.item_select));
else
holder.itemView.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.item_nselect));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition=position;
notifyItemChanged(selectedPosition);
}
});
}
#Override
public int getItemCount() {
return mProfiles.size();
}
}
}
Adapter Class,
package com.example.a123;
class adapter_for_research {
private String mName;
private int mImageId;
String getname() {
return mName;
}
void setname(String mName) {
this.mName = mName;
}
int getImageId() {
return mImageId;
}
void setImageId(int mImageId) {
this.mImageId = mImageId;
}
}
Is it possible to expand each holder like in onBindViewHolder? How to get the position and use isExpanded?
EDIT
Screenshot
So this is what I've done so far in my recyclerView using FirestoreRecyclerAdapter. I haven't figure out how to construct my xml and to expand it on my Adapter. I want to hide the seekbar first and show it when it gets expanded.
This is my Adapter
public class TaskAdapter extends FirestoreRecyclerAdapter <Activities, TaskAdapter.TaskHolder> {
private static final String TAG = "TaskAdapter";
TaskListener listener;
public TaskAdapter(#NonNull FirestoreRecyclerOptions<Activities> options, TaskListener listener) {
super(options);
this.listener = listener;
}
#Override
protected void onBindViewHolder(#NonNull TaskHolder holder, int position, #NonNull Activities activities) {
holder.tvTitle.setText(activities.getTitle());
}
#NonNull
#Override
public TaskHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.layout_list_tasks, parent, false);
return new TaskAdapter.TaskHolder(view);
}
class TaskHolder extends RecyclerView.ViewHolder{
TextView tvTitle, tvPercent;
ConstraintLayout expandableLayout;
public TaskHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvActivityTitle);
expandableLayout = itemView.findViewById(R.id.expandableLayout);
}
}
public interface TaskListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
}
This is my XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvActivityTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:ellipsize="end"
android:maxLines="1"
android:padding="16dp"
android:text="Title"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/expandableLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvActivityTitle">
<TextView
android:id="#+id/percent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="%"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatSeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
app:layout_constraintStart_toEndOf="#+id/percent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
For the love of god, I can't seem to figure this out. I have a tablayout with 3 tabs (each tab has in it a fragment). All i want to do is on the second fragment, the user clicks a button, and it replaces the second tab's fragment with a new fragment. So how do I go about doing that?
Here is my xml for the fragment I want to replace .
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragCards_mainLL">
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp"
android:id="#+id/fragCards_LL">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragCards_RecyclerView">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</FrameLayout>
And here is the fragment I want to replace the second tab's fragment.
<FrameLayout 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"
tools:context="com.daprlabs.swipedeck.ProfileView.FragmentFollowers"
android:id="#+id/fragFollowrs_mainFL">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Followers Fragment"
android:gravity="center"
android:textSize="30dp"/>
</FrameLayout>
Here is my viewpageAdapter code
public class ViewPagerAdapter extends FragmentPagerAdapter
{
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public ViewPagerAdapter(android.support.v4.app.FragmentManager fragmentManager)
{
super(fragmentManager);
}
#Override
public Fragment getItem(int position)
{
return fragments.get(position);
}
#Override
public int getCount()
{
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return tabTitles.get(position);
}
public void addFragments(Fragment fragment, String titles)
{
this.fragments.add(fragment);
this.tabTitles.add(titles);
}
}
Now somewhere in my Tab 2 fragment I have an onClickListener, I need to replace the entire fragment with a new fragment. I am not sure what to put in here...Currently, my "Followers Fragment" just goes beneath my recyclerview, so I can still see the views in the current, so it doesn't entirely replace the fragment...
#Override
public void onClick(View v)
{
FragmentFollowers f1 = new FragmentFollowers();
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragCards_LL,f1);
fragmentTransaction.setTransition(android.support.v4.app.FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Toast.makeText(getActivity(),"position " +position,Toast.LENGTH_SHORT).show();
}
attached you can find my problem and I would be very happy if somebody could help me out. I did several days of research and just can find my mistake. I want a custom listview with a clickable button which starts an activity. The activity is always the same but I need to know which item's button was clicked. For beeing able to see which button was clicked, I implemented a Toast but the onlything the Toast returns is 0 and 1.
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner java_spinner;
Spinner java_spinner2;
String mytext;
String mytext2;
TextView choosen_text;
TextView choosen_text2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
java_spinner = (Spinner)findViewById(R.id. spinner);
java_spinner.setOnItemSelectedListener(this);
java_spinner2 = (Spinner)findViewById(R.id. spinner_number_of_rounds);
java_spinner2.setOnItemSelectedListener(this);
ListView lv = (ListView) findViewById(R.id.listView);
generateListContent();
lv.setAdapter(new MyListAdaper(this, R.layout.custom_layout, data));
}
private ArrayList<String> data = new ArrayList<String>();
private void generateListContent() {
for(int i = 0; i < 55; i++) {
data.add("This is row number " + i);
}
}
private class MyListAdaper extends ArrayAdapter<String> {
private int layout;
private List<String> mObjects;
private MyListAdaper(Context context, int resource, List<String> objects) {
super(context, resource, objects);
mObjects = objects;
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewholder = null;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.itemImage);
viewHolder.title = (TextView) convertView.findViewById(R.id.listView);
viewHolder.button = (Button) convertView.findViewById(R.id.playbutton);
viewHolder.button.setTag(position);
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button of the following item was clicked at: " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
mainViewholder = (ViewHolder) convertView.getTag();
mainViewholder.title.setText(getItem(position));
return convertView;
}
}
public class ViewHolder {
ImageView thumbnail;
TextView title;
Button button;
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
View test1 = java_spinner.getSelectedView();
choosen_text = (TextView)test1 ;
mytext = choosen_text.getText().toString();
//Toast.makeText(this, "you selected" + mytext, Toast.LENGTH_SHORT).show();
View test2 = java_spinner2.getSelectedView();
choosen_text2 = (TextView)test2 ;
mytext2 = choosen_text2.getText().toString();
//Toast.makeText(this, "you selected" + mytext2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Keinen Bock mehr...?");
alertDialogBuilder
.setMessage("Ja und tschüss...!")
.setCancelable(false)
.setPositiveButton("Ja",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}}
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main"
tools:context="com.example.dominic.spinner.MainActivity"
android:background="#c0b7b7">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
android:background="#368260">
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginTop="12dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:entries="#array/days"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:spinnerMode="dropdown"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/linearLayout"
android:layout_alignEnd="#+id/linearLayout" />
<Spinner
android:entries="#array/pools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner2"
android:spinnerMode="dropdown"
android:layout_above="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_number_of_rounds"
android:entries="#array/Auswahl_der_Rundenanzahl"
android:layout_above="#+id/spinner2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:id="#+id/listView" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="125dp"
android:layout_height="90dp"
android:id="#+id/itemImage"
android:src="#mipmap/party"
android:layout_margin="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/listView"
android:layout_weight="2"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_weight="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PLAY"
android:id="#+id/playbutton" />
</LinearLayout>
</LinearLayout>
K Thx and Best,
Dominic
Hi i am very new in Android. I try to replace a fragment added statically in the layout file. But, if I instantiated my Fragment within my xml layout then the contents would remain visible after replacing it with another Fragment at runtime.
Here is my Activity Code:
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
public class RetailerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retailer);
}
public void selectFrag(View view) {
Fragment fr;
if (view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
} else if (view == findViewById(R.id.button3)) {
fr = new FragmentThree();
} else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fr);
fragmentTransaction.commit();
}
}
Here is my Activity XML file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment No.1" />
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment No.2" />
<Button
android:id="#+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment No.3" />
<LinearLayout
android:orientation="vertical"
android:id="#+id/fragment_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<fragment
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="fill_parent" />
</LinearLayout>
FragmentOne XML file:
<?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="#00ffff">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="This is fragment No.1"
android:textStyle="bold" />
</LinearLayout>
FragmentOne java file:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
FragmentTwo xml file:
<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="#00ffff">
<TextView
android:id="#+id/textfrag2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is fragment No.2"
android:textStyle="bold" />
</LinearLayout>
FragmentTwo java code:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
Thanks in advance.
I've looked into this problem too and I can't seem to find a solution for placing a fragment statically in the XML file. In your Activity XML file, you'll have to replace the Fragment portion with a FrameLayout (The id can stay the same, just replace 'Fragment' with 'FrameLayout'); only way to make your selectFrag method with FragmentTransaction replace the fragments without overlap.
(If you want to have a default fragment shown when the activity starts, duplicate the FragmentTransaction code in the onCreate method of the Activity and swap the blank FrameLayout view with either fragment)