This is what I mean by displaying twice. Both of them are able to scroll depending on where you place your finger.
I have a basic adapter that doesn't do anything other than load the view (which has some placeholder data seen above).
Here is where the view is referenced in the adapter:
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item_forecast, parent, false);
return view;
}
And the Adapter is call in a fragment here:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
ListView forecastListView = (ListView) rootView.findViewById(R.id.listView_forecast);
forecastListView.setAdapter(mForecastAdapter);
forecastListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, cursor.getLong(COL_WEATHER_DATE)
));
startActivity(intent);
}
}
});
return rootView;
}
I also have a cursor loader in that fragment that swaps the cursor onLoadFinished and onLoaderReset.
My layout.xml file, just in case it's relevant.
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for weather forecast list item for future day (not today) -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/list_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/list_item_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tomorrow"/>
<TextView
android:id="#+id/list_item_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/list_item_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="81"/>
<TextView
android:id="#+id/list_item_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="68"/>
</LinearLayout>
</LinearLayout>
Asked for my MainActivity.java:
public class MainActivity extends AppCompatActivity {
String LOG_TAG = MainActivity.class.getSimpleName();
private final String FORECASTFRAGMENT_TAG = "FFTAG";
String mLocation;
private void showMap(Uri zipCode){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(zipCode);
if(intent.resolveActivity(this.getPackageManager()) != null){
startActivity(intent);
}else{
View view = getCurrentFocus();
Snackbar.make(view, "No Map application found", Snackbar.LENGTH_SHORT).setAction("", null).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//
// mLocation = Utility.getPreferredLocation(this);
//
// Log.v(LOG_TAG, "onCreate()");
mLocation = Utility.getPreferredLocation(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new ForecastFragment(), FORECASTFRAGMENT_TAG)
.commit();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.v(LOG_TAG, "onDestroy()");
}
#Override
protected void onStart() {
super.onStart();
Log.v(LOG_TAG, "onStart()");
}
#Override
protected void onResume() {
super.onResume();
if(mLocation != Utility.getPreferredLocation(this)){
mLocation = Utility.getPreferredLocation(this);
ForecastFragment ff = (ForecastFragment)getSupportFragmentManager().findFragmentByTag(FORECASTFRAGMENT_TAG);
ff.onLocationChange();
}
Log.v(LOG_TAG, "onResume()");
}
#Override
protected void onStop() {
super.onStop();
Log.v(LOG_TAG, "onStop()");
}
#Override
protected void onPause() {
super.onPause();
Log.v(LOG_TAG, "onPause()");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Context context = getApplicationContext();
// int duration = Toast.LENGTH_SHORT;
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
// Toast toast = Toast.makeText(context, "Settings Pressed", duration);
// toast.show();
Intent intent = new Intent(context, SettingsActivity.class);
startActivity(intent);
return true;
}else if(id == R.id.action_map_view){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplication());
String zipCode = preferences.getString(getString(
R.string.pref_location_key),
getString(R.string.pref_location_default));
Uri geolocation = Uri.parse("geo:0,0?").buildUpon()
.appendQueryParameter("q", zipCode)
.build();
showMap(geolocation);
}
return super.onOptionsItemSelected(item);
}
}
This is the main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.example.android.sunshine.app.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<!--<android.support.design.widget.FloatingActionButton-->
<!--android:id="#+id/fab"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_gravity="bottom|end"-->
<!--android:layout_margin="#dimen/fab_margin"-->
<!--android:src="#android:drawable/ic_dialog_email" />-->
</android.support.design.widget.CoordinatorLayout>
And this is the content_main.xml that is referenced:
<fragment 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:id="#+id/fragment"
android:name="com.example.android.sunshine.app.ForecastFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_main" />
I have seen this sort of behavior before with fragments. It indicates that you have more than one fragment that has been attached to the activity. Each with its own functioning listview. I am unsure how this is happening as of yet in your code.
EDIT
Two fragments are being attached in the following places.
Once in your xml:
<fragment 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:id="#+id/fragment"
android:name="com.example.android.sunshine.app.ForecastFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_main" />
And once in your Activity:
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new ForecastFragment(), FORECASTFRAGMENT_TAG)
.commit();
To fix this, remove
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new ForecastFragment(), FORECASTFRAGMENT_TAG)
.commit();
in your onCreate() of your activity and you'll now have just one list displaying.
You don't need to add the fragment in the onCreate since you have declared it in the xml:
Remove this from your onCreate:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new ForecastFragment(),FORECASTFRAGMENT_TAG)
.commit();
}
And make it this:
#Override
protected void onCreate(Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mLocation = Utility.getPreferredLocation(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Related
I'm following the "developping android apps" course in Udacity and when I run the app (sunshine app for wheather) in a handset emulator, when I click on an item from the forecast list, it must show the details of the selected item, but the app crashes and it show the following error: "ScrollView can host only one direct child" you can see that my scrollview has only one child
here are the codes of the mainactivity, detailactivity, and the fragments:
(I removed importations)
MainActivity
public class MainActivity extends AppCompatActivity implements ForecastFragment.Callback{
private final String LOG_TAG = MainActivity.class.getSimpleName();
private final String FORECASTFRAGMENT_TAG = "FFTAG";
private static final String DETAILFRAGMENT_TAG = "DFTAG";
private String mLocation;
boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
mLocation = Utility.getPreferredLocation(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.weather_detail_container) != null) {
// The detail container view will be present only in the large-screen layouts
// (res/layout-sw600dp). If this view is present, then the activity should be
// in two-pane mode.
mTwoPane = true;
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.weather_detail_container, new DetailFragment(), DETAILFRAGMENT_TAG)
.commit();
}
} else {
mTwoPane = false;
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
protected void onResume() {
super.onResume();
String location = Utility.getPreferredLocation( this );
// update the location in our second pane using the fragment manager
if (location != null && !location.equals(mLocation)) {
ForecastFragment ff = (ForecastFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_forecast);
if ( null != ff ) {
ff.onLocationChanged();
}
DetailFragment df = (DetailFragment)getSupportFragmentManager().findFragmentByTag(DETAILFRAGMENT_TAG);
if ( null != df ) {
df.onLocationChanged(location);
}
mLocation = location;
}
}
#Override
public void onItemSelected(Uri contentUri) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle args = new Bundle();
args.putParcelable(DetailFragment.DETAIL_URI, contentUri);
DetailFragment fragment = new DetailFragment();
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.weather_detail_container, fragment, DETAILFRAGMENT_TAG)
.commit();
} else {
Intent intent = new Intent(this, DetailActivity.class)
.setData(contentUri);
startActivity(intent);
}
}
}
ForecastFragment
public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int FORECAST_LOADER = 0;
// For the forecast view we're showing only a small subset of the stored data.
// Specify the columns we need.
private static final String[] FORECAST_COLUMNS = {
// In this case the id needs to be fully qualified with a table name, since
// the content provider joins the location & weather tables in the background
// (both have an _id column)
// On the one hand, that's annoying. On the other, you can search the weather table
// using the location set by the user, which is only in the Location table.
// So the convenience is worth it.
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATE,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.LocationEntry.COLUMN_COORD_LAT,
WeatherContract.LocationEntry.COLUMN_COORD_LONG
};
// These indices are tied to FORECAST_COLUMNS. If FORECAST_COLUMNS changes, these
// must change.
static final int COL_WEATHER_ID = 0;
static final int COL_WEATHER_DATE = 1;
static final int COL_WEATHER_DESC = 2;
static final int COL_WEATHER_MAX_TEMP = 3;
static final int COL_WEATHER_MIN_TEMP = 4;
static final int COL_LOCATION_SETTING = 5;
static final int COL_WEATHER_CONDITION_ID = 6;
static final int COL_COORD_LAT = 7;
static final int COL_COORD_LONG = 8;
private ForecastAdapter mForecastAdapter;
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
public void onItemSelected(Uri dateUri);
}
public ForecastFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// The CursorAdapter will take data from our cursor and populate the ListView.
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
// We'll call our MainActivity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
((Callback) getActivity())
.onItemSelected(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, cursor.getLong(COL_WEATHER_DATE)
));
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(FORECAST_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
// since we read the location when we create the loader, all we need to do is restart things
void onLocationChanged( ) {
updateWeather();
getLoaderManager().restartLoader(FORECAST_LOADER, null, this);
}
private void updateWeather() {
FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity());
String location = Utility.getPreferredLocation(getActivity());
weatherTask.execute(location);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String locationSetting = Utility.getPreferredLocation(getActivity());
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
locationSetting, System.currentTimeMillis());
return new CursorLoader(getActivity(),
weatherForLocationUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mForecastAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mForecastAdapter.swapCursor(null);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.example.bassem.sunshine.app.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<fragment 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:id="#+id/fragment"
android:name="com.example.bassem.sunshine.app.ForecastFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_main" />
fragment_main.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ForecastFragment"
tools:showIn="#layout/activity_main">
<ListView
style="#style/ForecastListStyle"
android:id="#+id/listview_forecast"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
DetailActivity
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
Bundle arguments = new Bundle();
arguments.putParcelable(DetailFragment.DETAIL_URI, getIntent().getData());
DetailFragment fragment = new DetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.weather_detail_container, fragment)
.commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
DetailFragment
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
static final String DETAIL_URI = "URI";
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private ShareActionProvider mShareActionProvider;
private String mForecast;
private Uri mUri;
private static final int DETAIL_LOADER = 0;
private static final String[] DETAIL_COLUMNS = {
WeatherEntry.TABLE_NAME + "." + WeatherEntry._ID,
WeatherEntry.COLUMN_DATE,
WeatherEntry.COLUMN_SHORT_DESC,
WeatherEntry.COLUMN_MAX_TEMP,
WeatherEntry.COLUMN_MIN_TEMP,
WeatherEntry.COLUMN_HUMIDITY,
WeatherEntry.COLUMN_PRESSURE,
WeatherEntry.COLUMN_WIND_SPEED,
WeatherEntry.COLUMN_DEGREES,
WeatherEntry.COLUMN_WEATHER_ID,
// This works because the WeatherProvider returns location data joined with
// weather data, even though they're stored in two different tables.
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING
};
// These indices are tied to DETAIL_COLUMNS. If DETAIL_COLUMNS changes, these
// must change.
public static final int COL_WEATHER_ID = 0;
public static final int COL_WEATHER_DATE = 1;
public static final int COL_WEATHER_DESC = 2;
public static final int COL_WEATHER_MAX_TEMP = 3;
public static final int COL_WEATHER_MIN_TEMP = 4;
public static final int COL_WEATHER_HUMIDITY = 5;
public static final int COL_WEATHER_PRESSURE = 6;
public static final int COL_WEATHER_WIND_SPEED = 7;
public static final int COL_WEATHER_DEGREES = 8;
public static final int COL_WEATHER_CONDITION_ID = 9;
private ImageView mIconView;
private TextView mFriendlyDateView;
private TextView mDateView;
private TextView mDescriptionView;
private TextView mHighTempView;
private TextView mLowTempView;
private TextView mHumidityView;
private TextView mWindView;
private TextView mPressureView;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mUri = arguments.getParcelable(DetailFragment.DETAIL_URI);
}
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
mIconView = (ImageView) rootView.findViewById(R.id.detail_icon);
mDateView = (TextView) rootView.findViewById(R.id.detail_date_textview);
mFriendlyDateView = (TextView) rootView.findViewById(R.id.detail_day_textview);
mDescriptionView = (TextView) rootView.findViewById(R.id.detail_forecast_textview);
mHighTempView = (TextView) rootView.findViewById(R.id.detail_high_textview);
mLowTempView = (TextView) rootView.findViewById(R.id.detail_low_textview);
mHumidityView = (TextView) rootView.findViewById(R.id.detail_humidity_textview);
mWindView = (TextView) rootView.findViewById(R.id.detail_wind_textview);
mPressureView = (TextView) rootView.findViewById(R.id.detail_pressure_textview);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detailfragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// If onLoadFinished happens before this, we can go ahead and set the share intent now.
if (mForecast != null) {
mShareActionProvider.setShareIntent(createShareForecastIntent());
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast + FORECAST_SHARE_HASHTAG);
return shareIntent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
void onLocationChanged( String newLocation ) {
// replace the uri, since the location has changed
Uri uri = mUri;
if (null != uri) {
long date = WeatherContract.WeatherEntry.getDateFromUri(uri);
Uri updatedUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(newLocation, date);
mUri = updatedUri;
getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if ( null != mUri ) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(
getActivity(),
mUri,
DETAIL_COLUMNS,
null,
null,
null
);
}
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
// Read weather condition ID from cursor
int weatherId = data.getInt(COL_WEATHER_CONDITION_ID);
// Use placeholder Image
mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId));
// Read date from cursor and update views for day of week and date
long date = data.getLong(COL_WEATHER_DATE);
String friendlyDateText = Utility.getDayName(getActivity(), date);
String dateText = Utility.getFormattedMonthDay(getActivity(), date);
mFriendlyDateView.setText(friendlyDateText);
mDateView.setText(dateText);
// Read description from cursor and update view
String description = data.getString(COL_WEATHER_DESC);
mDescriptionView.setText(description);
// Read high temperature from cursor and update view
boolean isMetric = Utility.isMetric(getActivity());
double high = data.getDouble(COL_WEATHER_MAX_TEMP);
String highString = Utility.formatTemperature(getActivity(), high, isMetric);
mHighTempView.setText(highString);
// Read low temperature from cursor and update view
double low = data.getDouble(COL_WEATHER_MIN_TEMP);
String lowString = Utility.formatTemperature(getActivity(), low, isMetric);
mLowTempView.setText(lowString);
// Read humidity from cursor and update view
float humidity = data.getFloat(COL_WEATHER_HUMIDITY);
mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity));
// Read wind speed and direction from cursor and update view
float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED);
float windDirStr = data.getFloat(COL_WEATHER_DEGREES);
mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));
// Read pressure from cursor and update view
float pressure = data.getFloat(COL_WEATHER_PRESSURE);
mPressureView.setText(getActivity().getString(R.string.format_pressure, pressure));
mForecast = String.format("%s - %s - %s/%s", dateText, description, high, low);
if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(createShareForecastIntent());
}
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) { }
}
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.example.bassem.sunshine.app.DetailActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_detail" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_detail.xml
<fragment 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:id="#+id/weather_detail_container"
android:name="com.example.bassem.sunshine.app.DetailFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_detail" />
fragment_detail.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/detail_day_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detail_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/detail_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detail_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="#+id/detail_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detail_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/detail_humidity_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detail_wind_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detail_pressure_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
Probably an error when generating R. Try cleaning then rebuild. If that doesn't work, I'd suggest copying the whole fragment_detail.xml and create a new xml file to paste it there. Delete the old one of course, then clean and rebuild.
I am trying learn Android and building a very basic ListView, the data set up using ArrayAdapter is not showing up. My Activity code is:
MainActivity Class(default no changes)
`public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}`
**MainActivityFragment class**
public class MainActivityFragment extends Fragment {
private ListAdapter arrayAdapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> myEntries = new ArrayList<String>();
myEntries.add("Unix");
myEntries.add("Java");
myEntries.add("Android");
arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_forecast_item_textview, myEntries);
ListView listView = (ListView)inflater.inflate(R.layout.fragment_main, container, false).findViewById(R.id.list_view_forecast);
listView.setAdapter(arrayAdapter);
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
list_item_forecast.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:minHeight="?android:listPreferredItemHeight"
android:gravity="center_vertical"
android:text=""
android:id="#+id/list_forecast_item_textview">
</TextView>
fragment_main.xml
<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" 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:showIn="#layout/activity_main"
tools:context=".MainActivityFragment"
android:id="#+id/forecastFragment">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_view_forecast" />
<include layout="#layout/list_item_forecast" />
</FrameLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
All my application code is as above. I have tried tweaking the code and also tried this link but cannot get this to work. Please help.
The listview you setAdapter is not the listview you return in the fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> myEntries = new ArrayList<String>();
myEntries.add("Unix");
myEntries.add("Java");
myEntries.add("Android");
arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_forecast_item_textview, myEntries);
View view =inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView)view .findViewById(R.id.list_view_forecast);
listView.setAdapter(arrayAdapter);
return view ;
}
In my app I'm using a Toolbar. Now in inside my Toolbar I have two ImageViews. When the user clicks on any of the ImageViews I open different Fragment or Activity but in my case I'm not able to click on any of the ImageViews.
*.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_home"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#drawable/background"
android:elevation="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iv_home_about_us"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:src="#drawable/about" />
<ImageView
android:id="#+id/iv_home_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/iv_home_about_us"
android:layout_marginRight="10dp"
android:src="#drawable/search" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
<TextView
style="#style/text_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="05dp"
android:gravity="center"
android:text="Trending around me" />
<com.techmorphosis.wheretoday.SlidingTabs.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"></android.support.v4.view.ViewPager>
</LinearLayout>
Complete Code
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_screen, container, false);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (!bundle.isEmpty()) {
position = bundle.getInt(FROM_WHERE_ERROR_OCCURED);
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
latitude = SettingPreffrences.getLatitude(contextFrag);
longitude = SettingPreffrences.getLongitude(contextFrag);
if (latitude.equals("") && longitude.equals("")) {
commonFunctions.isLocationAvailable();
commonFunctions.replaceFragment(getActivity(), new ErrorFrag().newInstance(100, 0), false);
} else {
initialize();
}
}
private void initialize() {
toolbar = (Toolbar) view.findViewById(R.id.toolbar_home);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
// actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
// actionBar.setDisplayShowTitleEnabled(false);
ivAboutUs = (ImageView) toolbar.findViewById(R.id.iv_home_about_us);
ivSearch = (ImageView) toolbar.findViewById(R.id.iv_home_search);
pager = (ViewPager) view.findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(getActivity().getSupportFragmentManager()));
tabLayout = (SlidingTabLayout) view.findViewById(R.id.tabs);
tabLayout.setDistributeEvenly(true);
tabLayout.setSelectedIndicatorColors(Color.TRANSPARENT);
tabLayout.setViewPager(pager);
if (position == 0) {
pager.setCurrentItem(0, true);
} else if (position == 1) {
pager.setCurrentItem(1, true);
} else if (position == 2) {
pager.setCurrentItem(2, true);
}
ivAboutUs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(contextFrag, "Yess", Toast.LENGTH_SHORT).show();
}
});
ivSearch.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_home_about_us:
commonFunctions.replaceFragment(getActivity(), new AboutUsFrag(), false);
break;
case R.id.iv_home_search:
Intent intent = new Intent(contextFrag, SearchScreen.class);
contextFrag.startActivity(intent);
break;
}
}
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new TodayFrag();
}
if (position == 1) {
fragment = new TommorowFrag();
}
if (position == 2) {
fragment = new LaterFrag();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
You can't access the UI element in onCreateView method - EVER
Use onActivityCreated method , that tell the fragment the activity is fully created and ready to interact.
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
ImageView ivAboutUs = (ImageView) view.findViewById(R.id.iv_home_about_us);
ivAboutUs .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
This might be an issue where the touch events never reach the ImageViews because they were absorbed by something else. I ran into something similar where I was trying to put an onClickListener on an Imageview embedded in a list item. No matter how much I clicked on the imageView, something else was eating up the touch events(Most likely the View that makes up the ListView Item. I fixed the problem by changing the ImageView to an ImageButton and setting its background to null (So that the imageButton would look like an imageView and not an image button.) Once I did that, clicking the images worked for me. Try changing your ImageViews to look like this:
<ImageButton
android:id="#+id/iv_home_about_us"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:background="#null"
android:src="#drawable/about" />
<ImageView
android:id="#+id/iv_home_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/iv_home_about_us"
android:layout_marginRight="10dp"
android:background="#null"
android:src="#drawable/search" />
I hope this helps. Good luck.
I have an android fragment in which I bring google maps into. I am trying to add a android toolbar to the top.
My xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="#color/primary"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/statsSpin"
android:spinnerMode="dropdown"/>
</android.support.v7.widget.Toolbar>
<!-- Lots of fancy layout -->
<RelativeLayout
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</RelativeLayout>
</RelativeLayout>
When I run my app though, the android toolbar does not show up...
My fragment looks like this:
public class BreweryTappedMap extends Fragment {
public BreweryTappedMap(){}
String beerId = "";
GoogleMap mMap;
private SupportMapFragment fragment;
private GoogleMap map;
String userID;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_brewmap, container, false);
((ActionBarActivity)getActivity()).getSupportActionBar().setTitle("Your Maps");
Spinner spinner = (Spinner) rootView.findViewById(R.id.statsSpin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.mappage, R.layout.dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
switch (position) {
case 0:
break;
case 1:
// do whatever stuff you wanna do here
Fragment Fragment_one;
FragmentManager man= getActivity().getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BreweryMap();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
userID = prefs.getString("userID", null);
//add url
//call async to get breweries to add to
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, fragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
if (map == null) {
map = fragment.getMap();
String url = "myURL";
new GetVisitedBreweries(getActivity(), map).execute(url); }
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="#color/primary"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/statsSpin"
android:spinnerMode="dropdown"/>
</android.support.v7.widget.Toolbar>
<!-- Lots of fancy layout -->
<RelativeLayout
android:id="#+id/map"
android:layout_below="#+id/toolbar" <----- You need this
android:layout_width="match_parent"
android:layout_height="wrap_content">
</RelativeLayout>
</RelativeLayout>
You are using ToolBar widget, so you should set toolbar before use it:
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
if (toolbar != null) {
getActivity().setSupportActionBar(toolbar);
getActivity().getSupportActionBar().setTitle("Your Maps");
// ...
}
I am following a fragment example https://gist.github.com/daichan4649/2947119.
I am adding the fragment dynamically after button click event.But the fragment is overlapping with the button. And when I am pressing back key on this screen, activity is closed.
Need help to display only the fragment after button is clicked and if the back is pressed after adding fragment, then only the top fragment should be closed.
Here are my test code.
MainActivity.java
public class MainActivity extends FragmentActivity {
private static Button mBtn;
private static final String TAG_LIST = "list";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
return;
}
mBtn = (Button) findViewById(R.id.clickme);
mBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = getFragmentManager().findFragmentByTag(TAG_LIST);
if (fragment == null) {
fragment = TestListFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(android.R.id.content, fragment, TAG_LIST);
ft.commit();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
TestListFragment.java
public class TestListFragment extends ListFragment {
public static TestListFragment newInstance() {
return new TestListFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
ViewGroup rootView = (ViewGroup) inflater.inflate(android.R.id.content, container, false);
return rootView;
}
#SuppressLint("NewApi")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_column, R.id.text);
setListAdapter(adapter);
adapter.addAll(createDataList(10));
}
private static List<String> createDataList(int counts) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < counts; i++) {
list.add("i=" + i);
}
return list;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//Toast.makeText(getActivity(), "List Item Clicked", Toast.LENGTH_SHORT).show();
//On item click, launch the DialogFragment
TestDialogFragment moveFragment = new TestDialogFragment( );
moveFragment.show(getFragmentManager(), "Test List Fragment");
}
TestDilogFragment.java
public class TestDialogFragment extends DialogFragment {
private View testDialogFragment = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Fill the layout as per Your requirement
testDialogFragment = inflater.inflate(R.layout.activity_list_fragment, container);
return testDialogFragment;
}
}
activity-main.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/clickme"
android:text="ClickMe" />
</RelativeLayout>
activity_list_fragment.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Change your activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parentt" >
<Button
android:id="#+id/clickme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<FrameLayout
android:id="#+id/container"
android:layout_above="#id/clickme"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
>
</FrameLayout>
</RelativeLayout>
You have a Button at the bottom and a ViewGroup which is a FrameLayout at the top. You add the Fragment to the container.
And in ManiActivtiy change to
ft.add(R.id.container, fragment, TAG_LIST);