i'm trying to add a custom layout to my settings app for personalization options with a clickable header image that launches a web url but the main preference layout is already set by my settings activiy, how can i remove the parent view so my custom layout can be inflated?
public class DEMENTED extends SettingsPreferenceFragment implements
Preference.OnPreferenceChangeListener {
private static final String TAG = "DEMENTED";
private static final String KEY_DEMENTED_GITHUB = "https://github.com/cphelps76";
private static final String KEY_DEMENTED_HEADER = "logo";
private static final String KEY_GESTURE_SETTINGS = "prefs_gesture";
Preference mlogo;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.demented_interface, container);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.demented_interface_settings);
mlogo = findPreference(KEY_DEMENTED_HEADER);
Utils.updatePreferenceToSpecificActivityFromMetaDataOrRemove(getActivity(),
getPreferenceScreen(), KEY_GESTURE_SETTINGS);
}
#Override
protected int getMetricsCategory() {
return MetricsLogger.DEMENTED_INTERFACE;
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mlogo) {
launchUrl(KEY_DEMENTED_GITHUB);
return true;
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
final String key = preference.getKey();
return true;
}
private void launchUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent whatever = new Intent(Intent.ACTION_VIEW, uriUrl);
getActivity().startActivity(whatever);
}
}
I solved my own problem by inflating my bas preference view in OnCreateView and finding the imageview id and then making my image clickable and setting an onclick listener
public class DEMENTED extends SettingsPreferenceFragment implements
Preference.OnPreferenceChangeListener, View.OnClickListener {
private static final String TAG = "DEMENTED";
private static final String KEY_DEMENTED_GITHUB = "https://github.com/cphelps76";
private static final String KEY_GESTURE_SETTINGS = "prefs_gesture";
private static final String KEY_HARDWARE_KEYS = "prefs_buttons";
private ImageView mLogoView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.demented_interface_settings);
removePreferences();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.preference_list_fragment, parent, false);
mLogoView = (ImageView)rootView.findViewById(R.id.logo);
updateView();
return rootView;
}
private boolean hasButtons() {
return getResources().getInteger(
com.android.internal.R.integer.config_deviceHardwareKeys) != 0;
}
private void removePreference(Preference preference) {
getPreferenceScreen().removePreference(preference);
}
private void removePreferences() {
Utils.updatePreferenceToSpecificActivityFromMetaDataOrRemove(getActivity(),
getPreferenceScreen(), KEY_GESTURE_SETTINGS);
if (!hasButtons()) {
removePreference(KEY_HARDWARE_KEYS);
}
}
private void updateView() {
if (mLogoView != null) {
mLogoView.setClickable(true);
mLogoView.setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
if (v == mLogoView) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
launchUrl(KEY_DEMENTED_GITHUB);
}
}
#Override
protected int getMetricsCategory() {
return MetricsLogger.DEMENTED_INTERFACE;
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
final String key = preference.getKey();
return true;
}
private void launchUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent demented = new Intent(Intent.ACTION_VIEW, uriUrl);
getActivity().startActivity(demented);
}
}
Related
I am follow this link tutorial [https://developer.qualcomm.com/software/snapdragon-neural-processing-engine-ai/getting-started and i am able to download all model image but my requirement is now i need how to display gallery image in grid view my code is for model overview fragment:
public class ModelOverviewFragment extends Fragment {
public static final String EXTRA_MODEL = "model";
enum MenuRuntimeGroup {
SelectCpuRuntime(NeuralNetwork.Runtime.CPU),
SelectGpuRuntime(NeuralNetwork.Runtime.GPU),
SelectDspRuntime(NeuralNetwork.Runtime.DSP);
public static int ID = 1;
public NeuralNetwork.Runtime runtime;
MenuRuntimeGroup(NeuralNetwork.Runtime runtime) {
this.runtime = runtime;
}
}
private GridView mImageGrid;
private ModelImagesAdapter mImageGridAdapter;
private ModelOverviewFragmentController mController;
private TextView mDimensionsText;
private TextView mModelNameText;
private Spinner mOutputLayersSpinners;
private TextView mClassificationText;
private TextView mModelVersionText;
public static ModelOverviewFragment create(final Model model) {
final ModelOverviewFragment fragment = new ModelOverviewFragment();
final Bundle arguments = new Bundle();
arguments.putParcelable(EXTRA_MODEL, model);
fragment.setArguments(arguments);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_model, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mImageGrid = (GridView) view.findViewById(R.id.model_image_grid);
mImageGridAdapter = new ModelImagesAdapter(getActivity());
mImageGrid.setAdapter(mImageGridAdapter);
mImageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Bitmap bitmap = mImageGridAdapter.getItem(position);
mController.classify(bitmap);
}
});
mModelNameText = (TextView) view.findViewById(R.id.model_overview_name_text);
mModelVersionText = (TextView) view.findViewById(R.id.model_overview_version_text);
mDimensionsText = (TextView) view.findViewById(R.id.model_overview_dimensions_text);
mOutputLayersSpinners = (Spinner) view.findViewById(R.id.model_overview_layers_spinner);
mClassificationText = (TextView) view.findViewById(R.id.model_overview_classification_text);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
final Model model = getArguments().getParcelable(EXTRA_MODEL);
mController = new ModelOverviewFragmentController(
(Application) getActivity().getApplicationContext(), model);
}
#Override
public void onCreateOptionsMenu(android.view.Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
final SNPE.NeuralNetworkBuilder builder = new SNPE.NeuralNetworkBuilder(
(Application) (getActivity().getApplicationContext()));
for (MenuRuntimeGroup item : MenuRuntimeGroup.values()) {
if (builder.isRuntimeSupported(item.runtime)) {
menu.add(MenuRuntimeGroup.ID, item.ordinal(), 0, item.runtime.name());
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getGroupId() == MenuRuntimeGroup.ID) {
final MenuRuntimeGroup option = MenuRuntimeGroup.values()[item.getItemId()];
mController.setTargetRuntime(option.runtime);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
mController.attach(this);
}
#Override
public void onStop() {
mController.detach(this);
super.onStop();
}
public void addSampleBitmap(Bitmap bitmap) {
if (mImageGridAdapter.getPosition(bitmap) == -1) {
mImageGridAdapter.add(bitmap);
mImageGridAdapter.notifyDataSetChanged();
}
}
public void setNetworkDimensions(Map<String, int[]> inputDimensions) {
mDimensionsText.setText(Arrays.toString(inputDimensions.get("data")));
}
public void displayModelLoadFailed() {
mClassificationText.setVisibility(View.VISIBLE);
mClassificationText.setText(R.string.model_load_failed);
Toast.makeText(getActivity(), R.string.model_load_failed, Toast.LENGTH_SHORT).show();
}
public void setModelName(String modelName) {
mModelNameText.setText(modelName);
}
public void setModelVersion(String version) {
mModelVersionText.setText(version);
}
public void setOutputLayersNames(Set<String> outputLayersNames) {
mOutputLayersSpinners.setAdapter(new ArrayAdapter<>(
getActivity(), android.R.layout.simple_list_item_1,
new LinkedList<>(outputLayersNames)));
}
public void setClassificationResult(String[] classificationResult) {
if (classificationResult.length > 0) {
mClassificationText.setText(
String.format("%s: %s", classificationResult[0], classificationResult[1]));
}
mClassificationText.setVisibility(View.VISIBLE);
}
public void setLoadingVisible(boolean visible) {
mClassificationText.setVisibility(visible ? View.VISIBLE : View.GONE);
if (visible) {
mClassificationText.setText(R.string.loading_network);
}
}
public void displayModelNotLoaded() {
Toast.makeText(getActivity(), R.string.model_not_loaded, Toast.LENGTH_SHORT).show();
}
public void displayClassificationFailed() {
Toast.makeText(getActivity(), R.string.classification_failed, Toast.LENGTH_SHORT).show();
}
private static class ModelImagesAdapter extends ArrayAdapter<Bitmap> {
public ModelImagesAdapter(Context context) {
super(context, R.layout.model_image_layout);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).
inflate(R.layout.model_image_layout, parent, false);
} else {
view = convertView;
}
final ImageView imageView = ImageView.class.cast(view);
imageView.setImageBitmap(getItem(position));
return view;
}
}
}
for image loading code :
public class LoadImageTask extends AsyncTask<File, Void, Bitmap> {
private final ModelOverviewFragmentController mController;
private final File mImageFile;
public LoadImageTask(ModelOverviewFragmentController controller, final File imageFile) {
mController = controller;
mImageFile = imageFile;
}
#Override
protected Bitmap doInBackground(File... params) {
return BitmapFactory.decodeFile(mImageFile.getAbsolutePath());
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
mController.onBitmapLoaded(mImageFile, bitmap);
}
}
/*public class LoadImageTask extends AsyncTask{
private final ModelOverviewFragmentController mController;
private File path;
public LoadImageTask(ModelOverviewFragmentController controller, File jpeg)
{
mController=controller;
path=jpeg;
}
#Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
File file = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + path);
if(file.exists()){
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Log.d("ImagePath",bitmap.toString());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
mController.onBitmapLoaded(path,result);
}
}
for model :
public class Model implements Parcelable {
public static final Uri MODELS_URI = Uri.parse("content://snpe/models");
// public static final Uri MODELS_URI=Uri.parse("content://mtp://[usb:002,029]/Internal%20shared%20storage/DCIM");
public static final String INVALID_ID = "null";
public File file;
public String[] labels;
public File[] rawImages;
public File[] jpgImages;
public String name;
public File meanImage;
protected Model(Parcel in) {
name = in.readString();
file = new File(in.readString());
final String[] rawPaths = new String[in.readInt()];
in.readStringArray(rawPaths);
rawImages = fromPaths(rawPaths);
final String[] jpgPaths = new String[in.readInt()];
in.readStringArray(jpgPaths);
jpgImages = fromPaths(jpgPaths);
meanImage = new File(in.readString());
labels = new String[in.readInt()];
in.readStringArray(labels);
}
public Model() {}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(file.getAbsolutePath());
dest.writeInt(rawImages.length);
dest.writeStringArray(toPaths(rawImages));
dest.writeInt(jpgImages.length);
dest.writeStringArray(toPaths(jpgImages));
dest.writeString(meanImage.getAbsolutePath());
dest.writeInt(labels.length);
dest.writeStringArray(labels);
}
private File[] fromPaths(String[] paths) {
final File[] files = new File[paths.length];
for (int i = 0; i < paths.length; i++) {
files[i] = new File(paths[i]);
}
return files;
}
private String[] toPaths(File[] files) {
final String[] paths = new String[files.length];
for (int i = 0; i < files.length; i++) {
paths[i] = files[i].getAbsolutePath();
}
return paths;
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
#Override
public Model createFromParcel(Parcel in) {
return new Model(in);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
#Override
public String toString() {
return name.toUpperCase();
}
}
To load SD card images in grid view, please make few changes in loadImageSamples method of ModelOverviewFragmentController.java. Currently, the images are picked from snpe folder inside internal storage of the device and are populated on Grid View. To get all the images from the gallery, create AsyncTask class to load images from the Gallery to the Grid View with the help of Content Provider.
Please use this link https://stackoverflow.com/a/10877404 for code reference to load images on grid view.
Hope this helps!
Thank You
I opening Fragment B from Fragment A with startActivityForResult when Fragment B closes I get String value from EditText to Fragment A and everything works fine but now I opening same Fragment B from Fragment A and I want it to have that earlier returned value but it disappears
here I'm storing purposeText value from editText but not saving to json yet I want it to be saved on exiting Fragment A
public class Cloud {
private static final String JSON_ID = "id";
private static final String JSON_PURPOSE = "purpose";
private UUID mId;
private String purposeText = "";
public Cloud() {
mId = UUID.randomUUID();
}
public Cloud(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString(JSON_ID));
if (json.has(JSON_PURPOSE)){
purposeText = json.getString(JSON_PURPOSE);
}
}
public JSONObject toJSON() throws JSONException{
JSONObject json = new JSONObject();
json.put(JSON_ID, mId.toString());
json.put(JSON_PURPOSE, purposeText);
return json;
}
#Override
//Using get and set methods to get it in private String
public String getPurposeText(){return purposeText;}
public void setPurposeText(String purpose){purposeText = purpose;}
public UUID getId() {return mId;};
}
In Fragment A I'm getting text and setting it to textview and it works, then setting it back to setter in Cloud class
public class AddFragment extends Fragment {
private static final String TAG = "Cload";
public static final String EXTRA_DREAM_ID = "com.example.tadas.dreamcload1.dream_id";
private static final int REQUEST_DATE = 0;
private static final int REQUEST_TEXT =1;
private Cloud dCloud;
private TextView purposeView;
private String comeBackPurpose;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
dCloud = new Cloud();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().setTitle("Add new dream");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_add,parent,false);
purposeView = (TextView)v.findViewById(R.id.dream_purpose);
purposeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(),DreamPurposeActivity.class);
startActivityForResult(i,REQUEST_TEXT);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TEXT){
comeBackPurpose = data.getStringExtra("comeBackPurpose");
// Log.e(TAG,"SHITFACE " + comeBackPurpose);
purposeView.setText(comeBackPurpose);
dCloud.setPurposeText(comeBackPurpose);
Log.e(TAG,"SHITFACE " + dCloud.getPurposeText());
}
}
public static AddFragment newInstance(UUID dreamId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DREAM_ID, dreamId);
AddFragment fragment = new AddFragment();
fragment.setArguments(args);
return fragment;
}
}
Now In Fragment B I'm trying to set that text back to EditText in onCreateView method but it gets default value, what should I do to fix that?
public class PurposeFragment extends Fragment {
public static final String EXTRA_D = "com.dropstudio.drea.dr_ids";
private static final String TAG = "Cload";
private EditText purposeEText;
private String purposeEditText;
private Cloud mCloud;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCloud = new Cloud();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dream_purpose_edit,container,false);
purposeEText = (EditText)v.findViewById(R.id.purpose_edit);
purposeEText.setText(mCloud.getPurposeText());
return v;
}
public void savePurpose(){
purposeEditText = purposeEText.getText().toString();
mCloud.setPurposeText(purposeEditText);
Intent returnIntent = new Intent();
returnIntent.putExtra("comeBackPurpose",purposeEditText);
getActivity().setResult(Activity.RESULT_OK,returnIntent);
getActivity().finish();
}
public static PurposeFragment newInstance(UUID dreaIds) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_D, dreaIds);
PurposeFragment fragment = new PurposeFragment();
fragment.setArguments(args);
return fragment;
}
}
In Fragment B , you are creating a new Cloud object in onCreate() and trying to get the value from that object in onCreateView() which will always be null.
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCloud = new Cloud(); //New instance will be created
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dream_purpose_edit,container,false);
purposeEText = (EditText)v.findViewById(R.id.purpose_edit);
purposeEText.setText(mCloud.getPurposeText()); // 'mCloud' is a new object everytime and hence will not have your saved value
return v;
}
For your task, either use SharedPreferences or pass the saved value while instantiating Fragment B.
I am using a library to select date range, from here
link to that class
I don't know how to use DateRangePicker from fragment and how to use it, to store data.
Here is my code.
Fragment class:
public class LaborerProfile extends Fragment implements DateRangePickerFragment.OnDateRangeSelectedListener {
Switch switch1;
DateRangePickerFragment.OnDateRangeSelectedListener onDateRangeSelectedListener;
TextView Name,Phone_num,Skill,Age,Gender,Village;
RatingBar ratingBar;
String startDate;
String endDate;
public LaborerProfile() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
makeJsonArryReq();
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.laborer_profile, container, false);
switch1 = (Switch) rootView.findViewById(R.id.switch1);
Name = (TextView)rootView.findViewById(R.id.Name_L);
Phone_num = (TextView)rootView.findViewById(R.id.Phone_L);
Skill = (TextView)rootView.findViewById(R.id.Skill_L);
Age = (TextView)rootView.findViewById(R.id.Age_L);
Gender = (TextView)rootView.findViewById(R.id.Gender_L);
Village = (TextView)rootView.findViewById(R.id.Village_L);
ratingBar = (RatingBar) rootView.findViewById(R.id.Rating_L);
switch1.setChecked(true);
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
showDateRangePicker();
// /startActivity(new Intent(getActivity(),BusinessActivity.class));
} else {
}
}
});
if (switch1.isChecked()) {
} else {
}
return rootView;
}
public void showDateRangePicker(){
DateRangePickerFragment dateRangePickerFragment= DateRangePickerFragment.newInstance(onDateRangeSelectedListener, false);
dateRangePickerFragment.show(getFragmentManager(),"datePicker");
}
private void makeJsonArryReq() {
// showProgressDialog();
String URL_PROFILE_L="http://192.168.43.160/webservice/Lprofile.php?phone_num_l="+ Const.USER_ID;
Log.d("tirth", URL_PROFILE_L);
JsonArrayRequest req = new JsonArrayRequest(URL_PROFILE_L,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
if (!jsonObject.isNull("user_name_l")) {
Name.setText(jsonObject.getString("user_name_l"));
}
if (!jsonObject.isNull("phone_num_l")) {
Phone_num.setText(jsonObject.getString("phone_num_l"));
}
if (!jsonObject.isNull("age_l")){
Age.setText(jsonObject.getString("age_l"));
}
if (!jsonObject.isNull("gender_l")){
if(jsonObject.getString("gender_l").equals("1")){
Gender.setText("Male");
}else{
Gender.setText("Female");
}
}
if (!jsonObject.isNull("village_l")){
Village.setText(jsonObject.getString("village_l"));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// hideProgressDialog();
}
});
AppController.getInstance().addToRequestQueue(req);
}
#Override
public void onDateRangeSelected(int startDay, int startMonth, int startYear, int endDay, int endMonth, int endYear) {
Log.d("range : ","from: "+startDay+"-"+startMonth+"-"+startYear+" to : "+endDay+"-"+endMonth+"-"+endYear );
}
}
and I haven't changed the fragment provided from GitHub
public class DateRangePickerFragment extends DialogFragment implements View.OnClickListener{
private OnDateRangeSelectedListener onDateRangeSelectedListener;
private TabHost tabHost;
private DatePicker startDatePicker;
private DatePicker endDatePicker;
private Button butSetDateRange;
boolean is24HourMode;
public DateRangePickerFragment() {
// Required empty public constructor
}
public static DateRangePickerFragment newInstance(OnDateRangeSelectedListener callback, boolean is24HourMode) {
DateRangePickerFragment dateRangePickerFragment = new DateRangePickerFragment();
dateRangePickerFragment.initialize(callback, is24HourMode);
return dateRangePickerFragment;
}
public void initialize(OnDateRangeSelectedListener callback,
boolean is24HourMode) {
onDateRangeSelectedListener = callback;
this.is24HourMode = is24HourMode;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.date_range_picker, container, false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
tabHost = (TabHost) root.findViewById(R.id.tabHost);
butSetDateRange = (Button) root.findViewById(R.id.but_set_time_range);
startDatePicker = (DatePicker) root.findViewById(R.id.start_date_picker);
endDatePicker = (DatePicker) root.findViewById(R.id.end_date_picker);
butSetDateRange.setOnClickListener(this);
tabHost.findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec startDatePage = tabHost.newTabSpec("start");
startDatePage.setContent(R.id.start_date_group);
startDatePage.setIndicator("Start Date");
TabHost.TabSpec endDatePage = tabHost.newTabSpec("end");
endDatePage.setContent(R.id.end_date_group);
endDatePage.setIndicator("End Date");
tabHost.addTab(startDatePage);
tabHost.addTab(endDatePage);
return root;
}
#Override
public void onStart() {
super.onStart();
if (getDialog() == null)
return;
getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
}
public void setOnDateRangeSelectedListener(OnDateRangeSelectedListener callback) {
this.onDateRangeSelectedListener = callback;
}
#Override
public void onClick(View v) {
dismiss();
onDateRangeSelectedListener.onDateRangeSelected(startDatePicker.getDayOfMonth(),startDatePicker.getMonth(),startDatePicker.getYear(),
endDatePicker.getDayOfMonth(),endDatePicker.getMonth(),endDatePicker.getYear());
}
public interface OnDateRangeSelectedListener {
void onDateRangeSelected(int startDay, int startMonth, int startYear, int endDay, int endMonth, int endYear);
}
}
I have two buttons "start hotel1" and "start hotel2".
when you click on them, I create a fragment in which ViewPager:
public class PagerContainer extends Fragment {
static final int PAGE_COUNT = 2;
private String hotel;
public PagerContainer(String hotel) {
this.hotel = hotel;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.pager_container, null);
ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
PagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getActivity().getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Log.d("LOG", "onPageSelected, position = " + position);
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return v;
}
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return CalendarView.newInstance(position,hotel);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return "title";
}
}
}
I load it in another fragment that takes different parameters, depending on the button:
public class CalendarView extends Fragment {
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
static final String ARGUMENT_HOTEL = "arg_hotel";
private int pageNumber;
private String hotel;
static CalendarView newInstance(int page,String hotel) {
Log.d("myLOG","newInstance");
CalendarView calendarView = new CalendarView();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
arguments.putString(ARGUMENT_HOTEL, hotel);
calendarView.setArguments(arguments);
return calendarView;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.calendar, null);
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
hotel = getArguments().getString(ARGUMENT_HOTEL);
...
return v;
}
public class NewThread extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
...
}
#Override
protected void onPostExecute(String s) {
....
}
}
}
First pressing any key data normally loaded. After they loaded I click on the second button, and I have an empty screen. Log just says that the instance is not created. I need something to clean or rebuild? how?
case CONFEENCE_GRUP_NODE:
Fragment conference;
switch (position2) {
case HOLIDAY:
conference = new PagerContainer("holiday");
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.content_frame, conference).commit();
break;
case CITY:
conference = new PagerContainer("city");
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.content_frame, conference).commit();
break;
}
break;
Don't ever override the Fragment constructor, because they MUST have an empty constructor. Create the same newInstance method in your PagerContainer, and grab the parameter from it:
private static final String ARGUMENT_PAGE_HOTEL = "arg_page_hotel";
public PagerContainer() {
}
public static PagerContainer newInstance(String hotel) {
PagerContainer container = new PagerContainer();
Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_PAGE_HOTEL, hotel);
container.setArguments(arguments);
return container;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.pager_container, null);
hotel = getArguments().getString(ARGUMENT_PAGE_HOTEL);
...
return v;
}
I have MainActivity which has FragmentTabHost with several tabs. Each fragment in tab can be replaced with another fragment, so if we navigate back, we will see first displayed fragment for this tab (own stack for each tab). I have a quite working solution.
The below example demonstrates TabHost with 2 tabs and fragment classes for the first tab.
Is there any simpler, better or more elegant way to achieve this result?
AbstractPrimaryFragment.java. This class is a root fragment class that replaces fragments inside it. Other tab fragment classes can extend this superclass.
public abstract class AbstractPrimaryFragment extends Fragment {
// Simple framelayout.
private static final int RES_ID = R.layout.primary_fragment_layout;
protected static final int CONTENT_LAYOUT_ID = R.id.primary_fragment_layout;
protected Fragment mActiveFragment;
public AbstractPrimaryFragment()
{
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(RES_ID, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Check if active fragment is in layout, if not, make default fragment for this tab.
mActiveFragment = getChildFragmentManager().findFragmentById(CONTENT_LAYOUT_ID);
if (mActiveFragment == null)
{
mActiveFragment = makeDefaultActiveFragment();
String tag = getDefaultFragmentTag();
getChildFragmentManager().beginTransaction().add(CONTENT_LAYOUT_ID, mActiveFragment, tag).commit();
}
}
public boolean onBackPressed()
{
boolean backPressed = false;
final FragmentManager fragmentManager = getChildFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0)
{
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener()
{
#Override
public void onBackStackChanged()
{
mActiveFragment = fragmentManager.findFragmentById(CONTENT_LAYOUT_ID);
fragmentManager.removeOnBackStackChangedListener(this);
}
});
fragmentManager.popBackStack();
backPressed = true;
}
return backPressed;
}
protected abstract Fragment makeDefaultActiveFragment();
protected abstract String getDefaultFragmentTag(); }
Tab1PrimaryFragment.java
public class Tab1PrimaryFragment extends AbstractPrimaryFragment implements OnTab1Fragment1Listener {
private static final String FRAGMENT1_TAG = "tab1_fragment1";
private static final String FRAGMENT2_TAG = "tab2_fragment2";
#Override
protected Fragment makeDefaultActiveFragment()
{
return new Tab1Fragment1();
}
#Override
protected String getDefaultFragmentTag()
{
return FRAGMENT1_TAG;
}
#Override
public void onTab1Fragment1ButtonClick(Tab1Fragment1 tab1Fragment1)
{
Tab1Fragment2 tab1Fragment2 = new Tab1Fragment2();
getChildFragmentManager().beginTransaction().replace(CONTENT_LAYOUT_ID, tab1Fragment2, FRAGMENT2_TAG).addToBackStack(tab1Fragment1.getTag()).commit();
mActiveFragment = tab1Fragment2;
}}
Tab1Fragment1.class (default active fragment)
public class Tab1Fragment1 extends Fragment {
public interface OnTab1Fragment1Listener
{
public void onTab1Fragment1ButtonClick(Tab1Fragment1 tab1Fragment1);
}
private OnTab1Fragment1Listener mOnTab1Fragment1Listener;
public void setOnTab1Fragment1Listener(OnTab1Fragment1Listener onTab1Fragment1Listener)
{
mOnTab1Fragment1Listener = onTab1Fragment1Listener;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Fragment parentFragment = getParentFragment();
if (parentFragment != null && parentFragment instanceof OnTab1Fragment1Listener)
{
mOnTab1Fragment1Listener = (OnTab1Fragment1Listener) parentFragment;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Button button = new Button(getActivity());
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(mOnTab1Fragment1Listener != null)
{
mOnTab1Fragment1Listener.onTab1Fragment1ButtonClick(Tab1Fragment1.this);
}
}
});
return button; }}
Tab1Fragment2.java. Dummy fragment. This fragment is displayed when onTab1Fragment1ButtonClick is called.
public class Tab1Fragment2 extends Fragment {}
And MainActivity.java
public class MainActivity extends FragmentActivity {
private static final int RES_ID = R.layout.main_activity;
private static final int TAB_CONTENT_ID = android.R.id.tabcontent;
private static final int TABHOST_ID = android.R.id.tabhost;
private static final String TAB1_PRIMARY_FRAGMENT_TAG = "tab1_primary_fragment";
private static final String TAB2_PRIMARY_FRAGMENT_TAG = "tab2_primary_fragment"
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(RES_ID);
initializeTabHost();
}
private void initializeTabHost()
{
mTabHost = (FragmentTabHost) findViewById(TABHOST_ID);
mTabHost.setup(this, getSupportFragmentManager(), TAB_CONTENT_ID);
LayoutInflater inflater = LayoutInflater.from(this);
mTabHost.addTab(mTabHost.newTabSpec(TAB1_PRIMARY_FRAGMENT_TAG).setIndicator(inflater.inflate(R.layout.smth1, null)), Tab1PrimaryFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB2_PRIMARY_FRAGMENT_TAG).setIndicator(inflater.inflate(R.layout.smth2, null)), Tab2PrimaryFragment.class, null);
}
#Override
public void onBackPressed()
{
Fragment fragment = getSupportFragmentManager().findFragmentById(TAB_CONTENT_ID);
if (fragment != null && fragment instanceof AbstractPrimaryFragment)
{
if (((AbstractPrimaryFragment) fragment).onBackPressed())
{
return;
}
}
super.onBackPressed();
}}