ListView not showing on my app - java

I created a fragment connected to a list view to display a simple table view.
Here is my fragment:
public class ConfRoomListFragment extends Fragment {
ApplicationController activity;
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
"WebOS","Ubuntu","Windows7","Max OS X"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_conf_room_list, container, false);
activity = (ApplicationController) getActivity();
ArrayAdapter adapter = new ArrayAdapter<String>(getActivity(),
R.layout.activity_listview, mobileArray);
ListView listView = (ListView)view.findViewById(R.id.conf_room_directory);
listView.setAdapter(adapter);
return view;
}
}
Here is my fragment_conf_room_list.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:orientation="vertical">
<ListView
android:id="#+id/conf_room_directory"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Here is my activity_listview.xml:
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
When I run my app, all that shows is a blank screen. I created the list view and added the adapter. There doesn't seem to be any variable issues, so I'm not sure what the problem is.
EDIT
I've already added my fragment to the activity:
ApplicationController.java
/* Instantiate all Fragments needed*/
directoryViewFragment = new DirectoryViewFragment();
directoryListFragment = new DirectoryListFragment();
officeViewFragment = new OfficeViewFragment();
officeListFragment = new OfficeListFragment();
confRoomListFragment = new ConfRoomListFragment();
settingsFragment = new SettingsFragment();
directionsFragment = new DirectionsFragment();
airportInfoFragment = new AirportInfoFragment();
publicationsFragment = new PublicationsFragment();
practiceGroupListFragment = new PracticeGroupListFragment();
practiceGroupFragment = new PracticeGroupFragment();
As you can see I instantiated my fragment.
This is where the selection occurs:
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position, false);
System.out.println(position);
current_position = position;
invalidateOptionsMenu();
}
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position, boolean firstClick) {
// update the main content by replacing fragments
if (firstClick) {
Fragment fragment = directoryViewFragment;
currentPanel = Panel.HomeView;
getFragmentManager().beginTransaction()
.replace(R.id.fragmentHolder, fragment)
.addToBackStack(null)
.commit();
getFragmentManager().executePendingTransactions();
} else {
new ViewSelectionListener(this).onItemClick(null, null, position, 0);
}
// update selected item and title, then close the drawer
setTitle(navMenuTitles[position]);
drawerLayout.closeDrawer(navList);
}
I know it works because the setTitle function works and the title of the fragment is Conference Rooms.
This is my ViewSelectionListener.java, where I update the Fragment manager to show my fragment:
} else if (position == 2) {
//Conference Rooms
activity.setCurrentPanel(Panel.ConfRoomDirectory);
FragmentTransaction transaction = activity.getFragmentManager().beginTransaction()
.setCustomAnimations(Tags.TRANSITION_IN, Tags.TRANSITION_OUT)
// TODO If there are other fragments to hide, put them here!
.hide(activity.getDirectoryViewFragment())
.hide(activity.getPublicationsFragment())
.hide(activity.getSettingsFragment())
.hide(activity.getAirportInfoFragment())
.hide(activity.getDirectionsFragment())
.hide(activity.getPracticeGroupListFragment())
.hide(activity.getPracticeGroupFragment())
.hide(activity.getOfficeViewFragment())
.show(activity.getConfRoomListFragment());
if (activity.isPhone) {
transaction.hide(activity.getDirectoryListFragment());
transaction.hide(activity.getOfficeListFragment());
} else if (activity.isPortrait()) {
transaction.setCustomAnimations(R.animator.slide_in_left, R.animator.slide_out_left);
if (DirectoryViewFragment.leftPanelIsShowing) {
transaction.remove(activity.getDirectoryListFragment());
DirectoryViewFragment.leftPanelIsShowing = false;
}
if (OfficeViewFragment.leftPanelIsShowing) {
transaction.remove(activity.getOfficeListFragment());
OfficeViewFragment.leftPanelIsShowing = false;
}
if (PracticeGroupFragment.leftPanelIsShowing) {
transaction.remove(activity.getPracticeGroupListFragment());
PracticeGroupFragment.leftPanelIsShowing = false;
}
}
transaction.commit();
}
As you can see, I hide all of the other fragments and show the fragment that I wanted. However, only the title get updated, the fragment isn't shown. So the issue doesn't lie with the Activity, there's some other error that I don't see.

Check if onCreateView() method of your fragment is really called. If not then your fragment is not added to activity. Make sure to call
getFragmentManager().beginTransaction() .add(R.id.fragmentHolder, ConfRoomListFragment) .addToBackStack(null) .commit();
before you call FragmentTransaction's show(ConfRoomListFragment) method.
If ConfRoomListFragment's onCreate() method is called try to use next constructor of ArrayAdapter:
ArrayAdapter adapter = = new ArrayAdapter<>(getContext(), R.layout.activity_listview, mobileArray);
And change list item (activity_listview.xml) a little bit:
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16sp"
android:textStyle="bold" >
</TextView>

activity = (ApplicationController) getActivity();
Remove above line, this line will never use in this fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_conf_room_list, container, false);
ArrayAdapter adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mobileArray);
ListView listView = (ListView)view.findViewById(R.id.conf_room_directory);
listView.setAdapter(adapter);
return view;
}
fragment_conf_room_list.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:orientation="vertical">
<ListView
android:id="#+id/conf_room_directory"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>

You need to specify TextView layout in adapter if you want use your own layout.
public class ConfRoomListFragment extends Fragment {
ApplicationController activity;
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
"WebOS","Ubuntu","Windows7","Max OS X"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_conf_room_list, container, false);
activity = (ApplicationController) getActivity();
ArrayAdapter adapter = new ArrayAdapter<String>(getActivity(),
R.layout.activity_listview, R.id.label, mobileArray);
ListView listView = (ListView)view.findViewById(R.id.conf_room_directory);
listView.setAdapter(adapter);
return view;
}
}
And for your ListView height must be set to match_parent
<ListView
android:id="#+id/conf_room_directory"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

Related

Using BottomNavigationView outside of MainActivity in a Fragment

How do I use the bottomNavigationView variable outside of the MainActivity?
In MainActivity, I would use this to set and reove a badge
// To Add
BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(menuItemId);
badge.setVisible(true);
// To remove
bottomNavigationView.removeBadge(menuItem.getItemId());
However it will return null in a fragment if I try the same method
public BottomNavigationView bottomNavigationView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MainActivity main = new MainActivity();
main.bottomNavigationView.removeBadge(2131231026);
I have also tried this in the fragment, but nothing occurs
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_chat, container, false);
final View nav = inflater.inflate(R.layout.activity_main, container, false);
bottomNavigationView = nav.findViewById(R.id.bottomNav);
BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(2131231026);
badge.setVisible(false);
I don't know if you have this in Java (requireActivity) and if you have only one Activity in your project, but It can be the solution :
(requireActivity() as MainActivity).findViewById(R.id.bottomNav)
Also you can add function in your main Activity like addBadge / removeBadge.
But I think you can't get bottomNavigationView outside the main activity because it's part of UI mainActivity and not others fragments
PS : Your line " MainActivity main = new MainActivity();" isn't good because you instanciate an activity and not get actual instance so bottomNavigationView is null. May be use this.getActivity() ( this = fragment instance)
If you want to use BottmNavigationView outside of MainActivity first you should create a separate activity like MenuActivity and suppose you want to use 5 items in BottmNavigationView, so:
public class MenuActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
final Fragment fragment1 = new DiscoverFragment();
final Fragment fragment2 = new CreateFragment();
final Fragment fragment3 = new AnalyticsFragment();
final Fragment fragment4 = new MoreFragment();
final FragmentManager fm = getSupportFragmentManager();
final Fragment[] active = {fragment1};
fm.beginTransaction().add(R.id.main_container, fragment4, "4").hide(fragment4).commit();
fm.beginTransaction().add(R.id.main_container, fragment3, "3").hide(fragment3).commit();
fm.beginTransaction().add(R.id.main_container, fragment2, "2").hide(fragment2).commit();
fm.beginTransaction().add(R.id.main_container,fragment1, "1").commit();
bottomNavigationView=findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
fm.beginTransaction().hide(active[0]).show(fragment1).commit();
active[0] = fragment1;
return true;
case R.id.add:
fm.beginTransaction().hide(active[0]).show(fragment2).commit();
active[0] = fragment2;
return true;
case R.id.chart:
fm.beginTransaction().hide(active[0]).show(fragment3).commit();
active[0] = fragment3;
return true;
case R.id.more:
fm.beginTransaction().hide(active[0]).show(fragment4).commit();
active[0] = fragment4;
break;
}
return true;
}
});
}
}
XML view:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="MainActivity"
tools:showIn="#layout/activity_main"
android:padding="1dp"
android:id="#+id/main_container"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
app:itemIconSize="26dp"
app:itemTextAppearanceActive="#style/BottomNavigationView.Active"
app:itemTextAppearanceInactive="#style/BottomNavigationView"
app:itemIconTint="#drawable/navigation_view_colored"
app:itemTextColor="#drawable/navigation_view_colored"
app:labelVisibilityMode="labeled"
android:layout_gravity="bottom"
android:background="#android:color/white"
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="#menu/bottom_navigation_menu" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
be sure you created 5 fragments like DiscoverFragment, CreateFragment, and so on ...
and XML view of them.

fragment with the listview is not being replaced by the fragment with the textview

I want to have a activity with a image and then two fragments, one fragment with a list view and other fragment with a textview.
So, when the image is clicked i want to show the fragment with the list view and when the item on the fragment is clicked i want to replace the fragment with the listview with the fragment with the textview showing the text of the clicked list item.
Im doing this with the code below, but its not working, when an item of the list item is clicked the fragment with the listview is not replaced by the fragment with the textview so the list item text dont appears.
Main activity class:
public class MainActivity extends AppCompatActivity {
private ImageView img;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getFragmentManager();
img = (ImageView) findViewById(R.id.imageView);
}
private void addFragment() {
Fragment fragment = new Fragment();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.listviewInFragment, fragment, "frag");
transaction.commit();
}
public void AddFragmentList(View view) {
Fragment fragment = new Fragment();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.container, new FragmentA(), "frag");
transaction.commit();
}
}
main activity xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/image"
android:onClick="AddFragmentList"
tools:layout_editor_absoluteY="71dp"
tools:layout_editor_absoluteX="0dp" />
<FrameLayout
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.0"
tools:layout_editor_absoluteY="390dp">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
Fragment with the list view:
public class FragmentA extends Fragment{
private ListView listItems;
private String[] items = {
"item1",
"item2",
"item3",
"item4"
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listItems = (ListView) getView().findViewById(R.id.listviewInFragment);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, android.R.id.text1, items);
listItems.setAdapter(adapter);
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int positionCode = i;
String clickedValue = (String) adapterView.getItemAtPosition(i);
Toast.makeText(getActivity().getApplicationContext(), clickedValue, Toast.LENGTH_SHORT).show();
Bundle b = new Bundle();
b.putString("clickedValue", clickedValue);
FragmentA fragA = new FragmentA();
fragA.setArguments(b);
getFragmentManager().beginTransaction().replace(R.id.container, fragA);
}
});
}
}
Fragment with the list view xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0ff">
<ListView
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="16dp"
android:id="#+id/listviewInFragment"/>
</android.support.constraint.ConstraintLayout>
Fragment with the text view:
public class fragmentb extends Fragment {
private TextView tv;
Intent intent;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv = (TextView) getView().findViewById(R.id.textView);
Bundle b = this.getArguments();
if(b != null){
String clickedValue =b.getString("clickedValue");
tv.setText(clickedValue);
}
}
}
Fragment with the text view xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="17dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
/>
</android.support.constraint.ConstraintLayout>
Try this, may help you
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int positionCode = i;
String clickedValue = (String) adapterView.getItemAtPosition(i);
Toast.makeText(getActivity().getApplicationContext(), clickedValue, Toast.LENGTH_SHORT).show();
Bundle b = new Bundle();
b.putString("clickedValue", clickedValue);
FragmentB fragb = new FragmentB();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragb);
fragmentTransaction.commit();
}

Android - Fragment from ArrayAdapter

At the moment I have a activity with a viewpager which inflates a listfragment.
When a user click on a item in the listview I would like to inflate a new fragment.
Test.java
public class Test extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
final Toolbar toolbar;
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
ViewPager vp = (ViewPager) findViewById(R.id.n_Viewpager);
this.addPages(vp);
}
//ADD ALL PAGES
private void addPages(ViewPager pager) {
MyFragPagerAdapter adapter = new MyFragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new TestFragment());
//SET ADAPTER TO PAGER
pager.setAdapter(adapter);
}
}
layout.activity_test
<RelativeLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="tutorial.com.ScratchGolfer.Test">
<RelativeLayout
android:id="#+id/nav"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appbarr"
>
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/n_Viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/appbarr"
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"
/>
</RelativeLayout>
</RelativeLayout>
TestFragment.java
public class TestFragment extends ListFragment {
//Setting the name of each event
String[] options = {"1", "2", "3", "4", "5", "6", "7"};
ArrayAdapter<String> adapter;
//Inflating the view with the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
adapter = new ArrayAdapter<>(getActivity(), R.layout.listitem, R.id.textview, options);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
//Click events
#Override
public void onStart() {
super.onStart();
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int pos, long l) {
switch (pos) {
case 0:
Intent intent0 = new Intent(v.getContext(), NewActivity.class);
v.getContext().startActivity(intent0);
break;
case 1:
break;
}
}
});
}
}
I have managed to open a activity when I click a item in the listview, but I would like to inflate the current activity with a new fragment depending on what item is clicked in the listview
It's not the best and shortest solution, but I found it more understandable.
You can create a Fragment as container and add it to your ViewPager. Then replace fragments inside it.
fragment_container.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_container_root_view">
</LinearLayout>
ContainerFragment.Java
public class ContainerFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_container, container, false);
getChildFragmentManager().beginTransaction().replace(R.id.fragment_container_root_view, new TestFragment()).commit();
return view;
}
}
In you activity:
private void addPages(ViewPager pager) {
MyFragPagerAdapter adapter = new MyFragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new ContainerFragment());
//SET ADAPTER TO PAGER
pager.setAdapter(adapter);
}
In your TestFragment:
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int pos, long l) {
switch (pos) {
case 0:
getParentFragment().getChildFragmentManager().beginTransaction().replace(R.id.fragment_container_root_view, new SecondFragment()).addToBackStack("").commit();
break;
case 1:
break;
}
}
});
I didn't test this code to see if it has error or not, but with some changes, You can achieve to what you want.

Change view on button click from CustomAdapter

I have created a layout that contains a listView, the view is populated with multiple similar elements in the onCreateView function from a Fragment, the view is populated in the CustomAdapter extends BaseAdapter. In each element of the listView I have a button for which I want to implement a onClickListener. When the button is clicked I want to switch to another view, something similar to viewing comments on the GooglePlus mobile app.
I have tried doing so this way in the CustomAdapter:
public void setOnClickComment(View view) {
final ImageButton btn = (ImageButton)view.findViewById(R.id.addComment);
if (btn != null) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("ONCLICK", "I just clicked this shit" + btn.getTag());
manager.beginTransaction()
.replace(R.id.feedLayout, new CommentFragment()).commit();
}
});
} else {
Log.d("CLICK", "ESTE NULL");
}
}
The manager is a FragmentManager and it's passed from the fragment to the CustomAdapter constructor. I can see the Log in LogCat but that's it nothing else happens, the tag of the button is the position of the element.
This is the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/feedLayout"
>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
And in the fragment I inflate the above layout:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout linear = (LinearLayout) inflater.inflate(R.layout.swipe_screen_left, container, false);
view = (ListView) linear.getChildAt(0);
adapter = new CustomAdapter(getActivity(), data, getFragmentManager());
view.setAdapter(adapter);
return linear;
}

Click a button to open a Fragment?

I have a ViewPager in which I am able to view between 4 different tabs (which are fragments) I created. In one of my fragments, I want to have a button that will, after I click a button on that page, replace that view with another fragment. Now I don't want to swipe to another tab, I just merely want to replace the view of the current fragment when I press that button. Here is my attempt, but I'm not sure why when I click my button, nothing happens. If anyone could help me that would be great. Thanks!
This is the Fragment I call to create the view and the button I want to press.
ManualSelection.java
public class ManualSelection extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_manual_selection, container, false);
intent = new Intent(getActivity(), ManualSelectionListView.class);
return rootView;
}
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button listViewGenerated = (Button) getActivity().findViewById(R.id.manual_generate);
listViewGenerated.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
});
}
}
And here is the Fragment I want to create
ManualSelectionListView.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ManualSelectionListView extends Fragment {
static final String[] MOBILE_OS =
new String[] { "Android", "iOS", "WindowsMobile", "Blackberry"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.listview, container, false);
ListView lv = (ListView)rootView.findViewById(R.id.listview);
lv.setAdapter(new MobileArrayAdapter(getActivity(),MOBILE_OS));
return rootView;
}
}
And here are my XML files:
activity_manual_selection.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.ecs160.homestay.ManualSelection"
android:id="#+id/fragmentTest">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate"
android:id="#+id/manual_generate"
android:layout_centerHorizontal="true"
android:onClick="generateListView"/>
And here is the XML file called listview.xml that contains R.id.listView_manual
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView_manual">
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
I get nothing displayed when I hit "Generate." Any ideas? Thanks!
In your Activity you should create this:
public void generateListView(View v){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
The problem is that you are trying to get the Button id from your main activity which will return null
Button listViewGenerated = (Button) getActivity().findViewById(R.id.manual_generate);
Button manual_generate is located in your activity_manual_selection layout not in your Main activity's layout you cant get view from different layout or else it will return null
solution:
Get the Button's id from your fragment's layout
public class ManualSelection extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_manual_selection, container, false);
intent = new Intent(getActivity(), ManualSelectionListView.class);
Button listViewGenerated = (Button) rootView.findViewById(R.id.manual_generate);
listViewGenerated.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
});
return rootView;
}
remove onActivityCreated

Categories

Resources