Starting new activity from fragment starts a blank activity - java

I'm trying to make a basic Tourist app for my hometown. I have an onItemClickListener set on a listView. My goal is that when a list item is clicked, I want to open a new activity to show the user more information about the selected item(address, phone number, GPS location, etc). I set all the textviews in the fragment before I send the intent, so, when I setContentView, it should be displayed with all the accurate information already populated.
The problem is, when the list view is clicked, the activity starts a blank activity. There is no error message and the logCat shows that the textviews were updated correctly but they just aren't displaying correctly with the layout.
I've been working on this for days and would appreciate any help that anyone can give. Thanks in advance. Code is below.
**This is the fragment that holds the arrayList with the information to be displayed.
public class FoodFragment extends Fragment {
public FoodFragment() {
// Required empty public constructor
}
public TourSite currentSite;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sites_listview, container, false);
// Create an ArrayList of TourSite objects for main tab lists
final ArrayList<TourSite> tourSites = new ArrayList<TourSite>();
tourSites.add(new TourSite(R.string.ginasAddress, R.string.ginasNumber, R.string.ginasGPS,
R.string.ginasWeblink, R.drawable.pizza_100, R.string.ginasName));
tourSites.add(new TourSite(R.string.ninosAddress, R.string.ninosnumber, R.string.ninosGPS,
R.string.ninosWeblink, R.drawable.pizza_100, R.string.ninosName));
tourSites.add(new TourSite(R.string.topsAddress, R.string.topsDinerNumber,
R.string.topsDinerGPS, R.string.topsWeblink, R.drawable.restaurant_100,
R.string.topsName));
tourSites.add(new TourSite(R.string.goldenEagleAddress, R.string.goldenEagleNumber,
R.string.goldenEagleGPS, R.drawable.noodles_100, R.string.goldenEagleName));
//Creates adapter that displays tourSites on tabs
TourSiteListAdapter adapter = new TourSiteListAdapter(getActivity(), tourSites);
//finds the listview that were using to display the images and names
ListView listview = (ListView) rootView.findViewById(R.id.siteList);
listview.setAdapter(adapter);
//attaches Listener to listView in order to open new activity with further
// information about the toursite
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//finds the selected list item
currentSite = tourSites.get(position);
//inflates the layout we want to display using the intent below
LayoutInflater inflater1 = (LayoutInflater) getContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View root = inflater1.inflate(R.layout.list_item_info, null, true);
//finds the textViews in the layout that we want to update before
// displaying in activity
TextView addressView = (TextView) root.findViewById(R.id.addressView);
TextView numberView = (TextView) root.findViewById((R.id.numberView));
TextView gpsView = (TextView) root.findViewById(R.id.gpsView);
TextView weblinkView = (TextView) root.findViewById(R.id.weblinkView);
//some toursites dont have phone numbers or websites. This handles that
// while also updateding the content to be displayed
if (currentSite.hasAddress()) {
addressView.setText(currentSite.getmAddress());
addressView.setVisibility(View.VISIBLE);
} else {
addressView.setVisibility(View.GONE);
}
if (currentSite.hasPhone()) {
numberView.setText(currentSite.getmPhone());
numberView.setVisibility(View.VISIBLE);
} else {
numberView.setVisibility(View.GONE);
}
gpsView.setText(currentSite.getmGPSlink());
gpsView.setMovementMethod(LinkMovementMethod.getInstance());
if (currentSite.hasWeblink()) {
weblinkView.setText(currentSite.getmWeblink());
weblinkView.setVisibility(View.VISIBLE);
weblinkView.setMovementMethod(LinkMovementMethod.getInstance());
} else {
weblinkView.setVisibility(View.GONE);
}
//used these logs to make sure the textviews were being updated correctly
Log.d("addressView = ", addressView.getText().toString());
Log.d("numberView = ", numberView.getText().toString());
Log.d("gpsView = ", "" + gpsView.getText().toString());
Log.d("weblinkView = ", weblinkView.getText().toString());
//starts new activity that displays tourSite info
Intent showInfo = new Intent(getContext(), TourSiteInfo.class);
startActivity(showInfo);
}
});
return rootView;
}
}
**This is the activity that is supposed to display the layout, but is blank
public class TourSiteInfo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_info);
}
}
**This is the XML layout that is supposed to display
<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"
android:padding="24dp"
android:id="#+id/infoLayout">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="123 Main Ave, Newark, New Jersey"
android:id="#+id/addressView"
android:padding="16dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="123 Main Ave, Newark, New Jersey"
android:id="#+id/numberView"
android:padding="16dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="123 Main Ave, Newark, New Jersey"
android:id="#+id/gpsView"
android:padding="16dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="123 Main Ave, Newark, New Jersey"
android:id="#+id/weblinkView"
android:padding="16dp"/>
</LinearLayout>
***This is the mainActivity java that contains the viewPager and tabLayout
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewpager = (ViewPager) findViewById(R.id.viewpager);
CategoryAdapter adapter = new CategoryAdapter(this, getSupportFragmentManager());
viewpager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewpager);
}
}
**the mainAcivity XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/mainLayout">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
***LogCat when the app launches and list item is clicked
01/25 14:37:31: Launching app
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
D/addressView =: ​503 Frank E Rodgers Blvd N, Harrison, NJ 07029
D/numberView =: ​(973) 482-4883
D/gpsView =: ​(correct google link displays but stack overflow won't allow it)
D/weblinkView =: ​ginaspizzanj.com
I/Timeline: Timeline:Activity_launch_requestid
:com.example.android.tourguide
time:222869939
D/SecWifiDisplayUtil: Metadata value : none
D/ViewRootImpl: #1 mView =
com.android.internal.policy.
PhoneWindow$DecorView{d9020d4 I.E...... R.....ID 0,0-0,0}
D/ViewRootImpl: MSG_RESIZED_REPORT:
ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
W/DisplayListCanvas: DisplayListCanvas is started on unbinded
RenderNode (without mOwningView)
I/Timeline: Timeline: Activity_idle id:
android.os.BinderProxy#5ab3627 time:222870123
V/ActivityThread: updateVisibility : ActivityRecord{5e11572
token=android.os.BinderProxy#3d0da23
{com.example.android.tourguide/com.example.android.tourguide.MainActivity}} show : true
I've been researching and trying different solutions for days but nothing has worked yet.

So, I think you need to do UI initialization in TourSiteInfo class. Inflating and setting values in onItemClick doesn't make sense. It will just create a new view and will be GCed soon after the creation, the view created there doesn't have any relation with the TourSiteInfo activity.
So here is what you need to do.
Intent showInfo = new Intent(getContext(), TourSiteInfo.class);. After this you need to set all the site info to this intent as an extra value. You can refer this.
Extract info from the intent in TourSiteInfo.onCreate and set values to controls. The code will be exactly the same as you did in onItemClick.

Related

ListView not showing on my app

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>

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;
}

Drawer Navigation, it's fragments buttons doesn't find the right actionlistener

I've some problems with the drawer navigation. I've tried much and googled a lot but didn't find a solution.
I'm using a drawer navigation. There you have to fill it's frame layout with fragments.
That works fine, so for example:
I pick something in the drawer navigation and it's frame layout loads the fragment (startdisplay in my app) with buttons and textviews.
Now I click on one of the fragments buttons, this should call the actionlistener in the fragments java class (startdisplay.java), but instead it's not finding these actionlisteners (android studio also tells me that these are never used). I found out that the app is looking in the drawer navigation class (mainmenuactivity in my app).
My question is if there is a way that my app is looking directly in the fragments java class, because I can't put all my code in one class (mainmenuactivity). Of course this won't be my only fragment that I'd have to put in there.
Here is the code:
The XML of the Startdisplay 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="de.touristenfahrerforum.MarcelMoiser.Fragments.Startdisplay">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="114dp"
android:onClick="startButton"
android:text="Start"
android:textSize="50sp" />
....
The java class of the Startdisplay fragment:
public class Startdisplay extends Fragment
{
....
private Activity activity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_startdisplay, container, false);
loadTrackText = (TextView)view.findViewById(R.id.loadTrackText);
loadModeText = (TextView)view.findViewById(R.id.loadModeText);
loadBestlapText = (TextView)view.findViewById(R.id.loadBestlapText);
fileService = new Fileservice();
activity = this.getActivity();
return view;
}
....
/**
* Actionlistener für den Start Button
*/
public void startButton(View view) //!!!!!!!!!!!!!!This method should be called when the button is pressed <-------------------------------------------------------------
{
if(track != null)
{
if( ((LocationManager) activity.getSystemService(activity.LOCATION_SERVICE)).isProviderEnabled(LocationManager.GPS_PROVIDER))
{//GPS ist aktiviert
Intent intent = new Intent(activity, MainActivity.class);
intent.putExtra(V.TRACK_EXTRA, track); //Hier könnte man vll auch nur den String statt dem Objekt übergeben <------
intent.putExtra(V.MODE_EXTRA, mode);
intent.putExtra(V.BESTLAP_EXTRA, bestlap);
startActivity(intent);
}
else{}//Meldung geben das das GPS nicht aktiviert ist
}
else{}//else es muss erst eine Strecke geladen werden
}
....
The Mainmenu XML (Drawer Layout):
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_menu"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
And the Mainmenuactivity(where the app searches for the startButton actionlistener):
public class MainMenuActivity extends Activity
{
private String[] menuItems;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mTitle;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
//Standartwerte für die Einstellungen erzeugen
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
mTitle = getTitle();
menuItems = new String[]{"Peter","Susi","Elephant"};
mDrawerLayout = (DrawerLayout) findViewById(R.id.main_menu);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
//Holt sich den Wert für die Umrechnung zwischen PX und DP
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
V.LOGICAL_DENSITY = metrics.density;
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, menuItems));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position)
{
// Create a new fragment and specify the planet to show based on position
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new Startdisplay())
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(menuItems[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
}
I'm only testing, so the menuItems have no sense and it's always loading the Startdisplay fragment, whatever I click on. So like I already said, the app should use the actionlistener in the Startdisplay.java and should not search for it in the MainMenuActivity.java.
Thanks in advance
Your problem is that when you set the attribute android:onClick, the method is looked for in the context of this view. The context of the view is, of course, the activity and not the fragment, which is why Android can't find your method there. So you have two options:
Put the method into the activity and delegate to the fragment.
Use View.OnClickListener instead.
In general I personally don't really like using android:onClick anyway because it is very easy to break. If it doesn't work, it just silently fails, like in your case. Therefore, I would use the second way.
Call something like this in onCreateView() of the fragment:
view.findViewById(R.id.startButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do what you need
}
});

Android ListView's setOnItemClickListener from PopupWindow not called

I'm trying to show a ListView from a PopupWindow. but when I'm try to call ListView's setOnItemClickListener nothing to haapen. Here It Java file
PopupWindowActivity.java
public class PopupWindowActivity extends Activity {
String[] data = { "DATA 1", "DATA 2", "DATA 3", "DATA 4", "DATA 5", "DATA 6" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.main, null);
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ListView listView = (ListView) popupView.findViewById(R.id.listView1);
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,data));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
System.out.println("Item Clicked");
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(btnOpenPopup, 20, -5);
}
});
}
}
Here it is first xml file
a.xml
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/openpopup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Open Popup Window" />
</LinearLayout>
Here it inflate xml file
main.xml
<?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:background="#drawable/recording"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="30sp"
android:layout_marginLeft="30sp"
android:layout_marginRight="30sp"
android:layout_marginTop="100sp" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000" >
</ListView>
</RelativeLayout>
</LinearLayout>
What am I doing wrong?
Thanks
Just one minor change in your code and BOOOM your code will listen to you list click event
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true);
You forget to mention focusable setting true in PopupWindow constructor.
had the same problem, but in my case setFocusble(false) was required (and using ListPopupWindow was not a solution in my case as a lot of stuff in the project already used base PopupWindow's functionality including extending).
If someone in the same situation there is a kind of workaround based on bug discusson here (post #9)
The main idea is that ListView's hierarchy is still receives touch events so we can manually trigger onItemClick().
However this approach is not 100% identical to real ListView's touch handling (like there is no glow of selection while tapping a row) this done pretty well for me for the moment.
If someone has more precise solution of this problem, please share.
So, here is complete Adapter's code which can be used with ListView inside PopupWindow which is setFocusable(false):
private class CustomAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
private ListView mOwningListView;
public CustomAdapter(Context context, List<String> objects, ListView listView) {
super(context, android.R.layout.simple_list_item_1, objects);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mOwningListView = listView;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.font_pick_row, null);
}
// this is the key point of workaround
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* as every row is still receiving their touches
* we can use this to manually trigger onItemClick
* since it doesn't firing in popupWindow.setFocusable(false)
*/
mOwningListView.getOnItemClickListener().onItemClick(mOwningListView, v, position, getItemId(position));
}
});
//... other stuff
return convertView;
}
}
May this help you
.
Declare listview and list onClickListener outside the button ClickListener.

android: creating a textfield display on the same activity with a ListActivity

I have an activity that pulls a String Array from xml and displays a ListActivity (the class extends ListActivity) and I'd like to know if it is possible to also display a textfield or textView below the list?
If so, what method should I research to do this? Have code samples?
Thanks!
CODE:
public class txchl extends ListActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//setContentView(R.layout.main);
String[] rmenu = getResources().getStringArray(R.array.root_menu);
if (rmenu != null) {
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, rmenu));
}
TextView tv = new TextView(this);
tv.setText("Hello");
setContentView(tv);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//
if (position == 4 || position == 5) {
Intent myIntent = new Intent(v.getContext(), Activity2.class);
myIntent.putExtra("com.activity.Key", position);
startActivity(myIntent);
} else {
Intent myIntent = new Intent(v.getContext(), txchl_hb.class);
myIntent.putExtra("com.activity.Key", position);
//myIntent.putExtra("com.activity.Dir", directives[position]);
startActivity(myIntent);
}
}
}
What you want is a vertical LinearLayout that contains a ListView and a TextView
There is an example of what you want to achieve in the android reference:
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "#android:id/list" (or list if it's in code)
http://developer.android.com/reference/android/app/ListActivity.html
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>

Categories

Resources