I'm trying to convert a TimePicker preference dialog extended from android.support.v7.preference.DialogPreference to the same but extended from androidx.preference.DialogPreference.
Here is the code of the original custom preference :
package com.example.example;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;
public class TimePreference extends DialogPreference {
private int mHour = 0;
private int mMinute = 0;
private TimePicker picker = null;
private final String DEFAULT_VALUE = "00:00";
public static int getHour(String time) {
String[] pieces = time.split(":");
return Integer.parseInt(pieces[0]);
}
public static int getMinute(String time) {
String[] pieces = time.split(":");
return Integer.parseInt(pieces[1]);
}
public TimePreference(Context context) {
this(context, null);
}
public TimePreference(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TimePreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
public void setTime(int hour, int minute) {
mHour = hour;
mMinute = minute;
String time = toTime(mHour, mMinute);
persistString(time);
notifyDependencyChange(shouldDisableDependents());
notifyChanged();
}
public String toTime(int hour, int minute) {
return hour + ":" + minute;
}
public void updateSummary() {
String time = mHour + ":" + mMinute;
setSummary(time24to12(time));
}
#Override
protected View onCreateDialogView() {
picker = new TimePicker(getContext());
return picker;
}
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
picker.setCurrentHour(mHour);
picker.setCurrentMinute(mMinute);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
int currHour = picker.getCurrentHour();
int currMinute = picker.getCurrentMinute();
if (!callChangeListener(toTime(currHour, currMinute))) {
return;
}
// persist
setTime(currHour, currMinute);
updateSummary();
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
String time = null;
if (restorePersistedValue) {
if (defaultValue == null) {
time = getPersistedString(DEFAULT_VALUE);
}
else {
time = getPersistedString(DEFAULT_VALUE);
}
}
else {
time = defaultValue.toString();
}
int currHour = getHour(time);
int currMinute = getMinute(time);
// need to persist here for default value to work
setTime(currHour, currMinute);
updateSummary();
}
public static Date toDate(String inTime) {
try {
DateFormat inTimeFormat = new SimpleDateFormat("HH:mm", Locale.US);
return inTimeFormat.parse(inTime);
} catch(ParseException e) {
return null;
}
}
public static String time24to12(String inTime) {
Date inDate = toDate(inTime);
if(inDate != null) {
DateFormat outTimeFormat = new SimpleDateFormat("hh:mm a", Locale.US);
return outTimeFormat.format(inDate);
} else {
return inTime;
}
}
}
If I try to use that directly in my preference fragment, the app crashed with the following error :
android.view.InflateException: Binary XML file line #27: Error inflating class com.example.example.TimePreference
...
Caused by: java.lang.ClassCastException: com.example.example.TimePreference cannot be cast to androidx.preference.Preference
That's normal, considering the fact that my custom preference is not an androidx.preference
I haven't found any information on how to convert an old android.support.v7.preference to a new androidx.preference. Does anyone know how to do so ?
Thanks a lot !
Related
I have an activity named Cardview Activity which has a recycler view associated with it and i am fetching data from a JSON asset file in that. But now when i click on an item of Cardview Activity, I want to send data related to that item only to another activity i.e. People_List_Activity which is again having a recyclerView.
CardViewActivity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Telephone Directory");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
String Office_Phone = jobIn.getString("Office_Phone");
String Residence_Phone = jobIn.getString("Residence_Phone");
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
// JSONObject jobI = fax.getString(k);
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("DirectoryData.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
RecyclerViewAdapterMain
package com.example.android.directory;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Android on 3/17/2017.
*/
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
}
});
}
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, int position) {
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
People_List_Activity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class PeopleListActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people_list);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Staff List");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
}
}
RecyclerViewAdapter_People.java
package com.example.android.directory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Android on 3/20/2017.
*/
public class RecyclerViewAdapter_People extends RecyclerView.Adapter<RecyclerViewAdapter_People.PeopleObjectHolder> {
private static String TAG = "peopleRecyclrVwAdptr";
public static class PeopleObjectHolder extends RecyclerView.ViewHolder{
TextView peopleName,peopleDesignation;
public PeopleObjectHolder(View itemView) {
super(itemView);
peopleName=(TextView)itemView.findViewById(R.id.people_name);
peopleDesignation=(TextView)itemView.findViewById(R.id.people_designation);
Log.d(TAG, "PeopleObjectHolder: ");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public PeopleObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_people_list_row,parent,false);
PeopleObjectHolder peopleObjectHolder=new PeopleObjectHolder(view);
return peopleObjectHolder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter_People.PeopleObjectHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
CategoryModel.java:
package com.example.android.directory;
import java.util.ArrayList;
/**
* Created by Android on 3/17/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList>categoryList;
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public static class CategoryList{
private int Category_id;
private String Category_name;
private ArrayList<String>Emails;
private ArrayList<String>Epabx;
private ArrayList<String>Category_Fax;
private ArrayList<Persons> persons;
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
public static class Persons{
private int Person_ID;
private String Name;
private String Designation;
private String Office_Phone;
private String Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
public Persons(int person_ID, String name, String designation, String office_Phone,
String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
}
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public String getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(String office_Phone) {
Office_Phone = office_Phone;
}
public String getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(String residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
}
}
how can i send the Person_Id, Name and Designation to the People_List_Activity ? Please help as i am stuck in the code.
You can send using Intent , by passing your data in Bundle and then pass Bundle into Intent Extras.When you go form one Activity to another .
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key1",value1);
bundle.putString("key2",value2);
bundle.putString("key3",value3);
intent.putExtras(bundle)
startActvity(intent);
And You can retrieve Data in next Activity OnCreate():
Bundle bundle = getIntent().getExtras();
String value1 = bundle.getString("key1");
String value2 = bundle.getString("key2");
String value3 = bundle.getString("key3");
please i have problem with gifview.
I think so what i need is:
I need put my gifimage to RAM memory.
package com.paradox02.dell.dormation01;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class GifView extends View{
// int pom=0;
private final static String STORETEXT6="index2.txt";
public static int indexG2;
int[] images = {
R.drawable.troj1,R.drawable.troj2,R.drawable.troj3,R.drawable.troj4,R.drawable.troj5, //0-4
R.drawable.koc1,R.drawable.koc5,R.drawable.koc3,R.drawable.koc4,R.drawable.koc2,//5-9
R.drawable.kruh1,R.drawable.kruh2,R.drawable.kruh3, ///10-12
R.drawable.tutorial1,
R.drawable.tutorial2,
R.drawable.tutorial3,
R.drawable.nic,
};
private InputStream gifInputStream;
private Movie gifMovie;
private int movieWidth, movieHeight;
private long movieDuration;
private long movieStart;
private Integer index2;
private Context co;
public GifView(Context context) {
super(context);
co = context;
init(context);
}
public GifView(Context context, AttributeSet attrs) {
super(context, attrs);
co = context;
init(context);
}
public GifView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
co = context;
init(context);
}
private void init(Context context) {
setFocusable(true);
//read();
gifInputStream = context.getResources().openRawResource(images[indexG2]);
gifMovie = Movie.decodeStream(gifInputStream);
movieWidth = gifMovie.width();
movieHeight = gifMovie.height();
movieDuration = gifMovie.duration();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(movieWidth, movieHeight);
}
#Override
protected void onDraw(Canvas canvas) {
long now = SystemClock.uptimeMillis();
if(movieStart == 0) {
movieStart = now;
}
read();
new Thread(new Runnable() {
public void run() {
gifMovie = Movie.decodeStream(gifInputStream);
movieWidth = gifMovie.width();
movieHeight = gifMovie.height();
movieDuration = gifMovie.duration();
}
}).start();
}
if(gifMovie != null) {
int dur = gifMovie.duration();
if(dur == 0) {
dur = 1000;
}
int relTime = (int)((now - movieStart) % dur);
gifMovie.setTime(relTime);
gifMovie.draw(canvas, 0, 0);
invalidate();
}
}
public void read() {
try {
InputStream in3 = getContext().openFileInput(STORETEXT6);
if (in3 != null) {
InputStreamReader tmp = new InputStreamReader(in3);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuilder buf3 = new StringBuilder();
while ((str = reader.readLine()) != null) {
buf3.append(str);
}
in3.close();
indexG2=Integer.valueOf(buf3.toString().trim());
}
} catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
} catch (Throwable t) {
}
}
}
I try put some code to Thread (runable) to acceleration.
I call this class on Main code:
gifView2 = (GifView2) findViewById(R.id.gif_view2);
<com.paradox02.dell.dormation01.GifView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/gif_view"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerInside"/>
app is public on Google Play
app in GP
while I play app sometimes all process crashed and write on display "load Launcher"
Please help me.
Thanks for any suggest.
If you need more code, write => I will put.
Excuse me for my easy English
I am trying to fetch the value of a Datepicker inside one of my fragments . I've read the documentation about Fragments in the Android Developer Guide.
Here is my Fragment layout :
<ir.smartlab.persindatepicker.PersianDatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/btnCheckFal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/relativeLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="#string/CheckFal" />
</RelativeLayout>
This is my java class for the fragment :
import ir.smartlab.persindatepicker.util.PersianCalendar;
public class HomeFragment extends Fragment {
private View btnCheckFalAction;
private PersianDatePicker persianDatePicker;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
btnCheckFalAction = (Button) rootView.findViewById(R.id.btnCheckFal);
PersianCalendar pCal = persianDatePicker.getDisplayPersianDate();
btnCheckFalAction.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getActivity(), "Date is : " + pCal , Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
pCal in above class return error "Cannot refer to a non-final variable pCal inside an inner class ..."
and here is the DatePicker class:
package ir.smartlab.persindatepicker;
import info.androidhive.slidingmenu.R;
import ir.smartlab.persindatepicker.util.PersianCalendar;
import ir.smartlab.persindatepicker.util.PersianCalendarConstants;
import ir.smartlab.persindatepicker.util.PersianCalendarUtils;
import java.util.Date;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
public class PersianDatePicker extends LinearLayout {
private NumberPicker yearNumberPicker;
private NumberPicker monthNumberPicker;
private NumberPicker dayNumberPicker;
private int minYear;
private int maxYear;
private int yearRange;
public PersianDatePicker(Context context) {
this(context, null, -1);
}
public PersianDatePicker(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public PersianDatePicker(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.sl_persian_date_picker, this);
yearNumberPicker = (NumberPicker) view.findViewById(R.id.yearNumberPicker);
monthNumberPicker = (NumberPicker) view.findViewById(R.id.monthNumberPicker);
dayNumberPicker = (NumberPicker) view.findViewById(R.id.dayNumberPicker);
PersianCalendar pCalendar = new PersianCalendar();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PersianDatePicker, 0, 0);
yearRange = a.getInteger(R.styleable.PersianDatePicker_yearRange, 10);
/*
* Initializing yearNumberPicker min and max values If minYear and
* maxYear attributes are not set, use (current year - 10) as min and
* (current year + 10) as max.
*/
minYear = a.getInt(R.styleable.PersianDatePicker_minYear, pCalendar.getPersianYear() - yearRange);
maxYear = a.getInt(R.styleable.PersianDatePicker_maxYear, pCalendar.getPersianYear() + yearRange);
yearNumberPicker.setMinValue(minYear);
yearNumberPicker.setMaxValue(maxYear);
int selectedYear = a.getInt(R.styleable.PersianDatePicker_selectedYear, pCalendar.getPersianYear());
if (selectedYear > maxYear || selectedYear < minYear) {
throw new IllegalArgumentException(String.format("Selected year (%d) must be between minYear(%d) and maxYear(%d)", selectedYear, minYear, maxYear));
}
yearNumberPicker.setValue(selectedYear);
yearNumberPicker.setOnValueChangedListener(dateChangeListener);
/*
* initializng monthNumberPicker
*/
boolean displayMonthNames = a.getBoolean(R.styleable.PersianDatePicker_displayMonthNames, false);
monthNumberPicker.setMinValue(1);
monthNumberPicker.setMaxValue(12);
if (displayMonthNames) {
monthNumberPicker.setDisplayedValues(PersianCalendarConstants.persianMonthNames);
}
int selectedMonth = a.getInteger(R.styleable.PersianDatePicker_selectedMonth, pCalendar.getPersianMonth());
if (selectedMonth < 1 || selectedMonth > 12) {
throw new IllegalArgumentException(String.format("Selected month (%d) must be between 1 and 12", selectedMonth));
}
monthNumberPicker.setValue(selectedMonth);
monthNumberPicker.setOnValueChangedListener(dateChangeListener);
/*
* initializiing dayNumberPicker
*/
dayNumberPicker.setMinValue(1);
dayNumberPicker.setMaxValue(31);
int selectedDay = a.getInteger(R.styleable.PersianDatePicker_selectedDay, pCalendar.getPersianDay());
if (selectedDay > 31 || selectedDay < 1) {
throw new IllegalArgumentException(String.format("Selected day (%d) must be between 1 and 31", selectedDay));
}
if (selectedMonth > 6 && selectedMonth < 12 && selectedDay == 31) {
selectedDay = 30;
} else {
boolean isLeapYear = PersianCalendarUtils.isPersianLeapYear(selectedYear);
if (isLeapYear && selectedDay == 31) {
selectedDay = 30;
} else if (selectedDay > 29) {
selectedDay = 29;
}
}
dayNumberPicker.setValue(selectedDay);
dayNumberPicker.setOnValueChangedListener(dateChangeListener);
a.recycle();
}
NumberPicker.OnValueChangeListener dateChangeListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int year = yearNumberPicker.getValue();
boolean isLeapYear = PersianCalendarUtils.isPersianLeapYear(year);
int month = monthNumberPicker.getValue();
int day = dayNumberPicker.getValue();
if (month < 7) {
dayNumberPicker.setMinValue(1);
dayNumberPicker.setMaxValue(31);
} else if (month > 6 && month < 12) {
if (day == 31) {
dayNumberPicker.setValue(30);
}
dayNumberPicker.setMinValue(1);
dayNumberPicker.setMaxValue(30);
} else if (month == 12) {
if (isLeapYear) {
if (day == 31) {
dayNumberPicker.setValue(30);
}
dayNumberPicker.setMinValue(1);
dayNumberPicker.setMaxValue(30);
} else {
if (day > 29) {
dayNumberPicker.setValue(29);
}
dayNumberPicker.setMinValue(1);
dayNumberPicker.setMaxValue(29);
}
}
}
};
public Date getDisplayDate() {
PersianCalendar displayPersianDate = new PersianCalendar();
displayPersianDate.setPersianDate(yearNumberPicker.getValue(), monthNumberPicker.getValue(), dayNumberPicker.getValue());
return displayPersianDate.getTime();
}
public void setDisplayDate(Date displayDate) {
setDisplayPersianDate(new PersianCalendar(displayDate.getTime()));
}
public PersianCalendar getDisplayPersianDate() {
PersianCalendar displayPersianDate = new PersianCalendar();
displayPersianDate.setPersianDate(yearNumberPicker.getValue(), monthNumberPicker.getValue(), dayNumberPicker.getValue());
return displayPersianDate;
}
public void setDisplayPersianDate(PersianCalendar displayPersianDate) {
int year = displayPersianDate.getPersianYear();
int month = displayPersianDate.getPersianMonth();
int day = displayPersianDate.getPersianDay();
if (month > 6 && month < 12 && day == 31) {
day = 30;
} else {
boolean isLeapYear = PersianCalendarUtils.isPersianLeapYear(year);
if (isLeapYear && day == 31) {
day = 30;
} else if (day > 29) {
day = 29;
}
}
dayNumberPicker.setValue(day);
minYear = year - yearRange;
maxYear = year + yearRange;
yearNumberPicker.setMinValue(minYear);
yearNumberPicker.setMaxValue(maxYear);
yearNumberPicker.setValue(year);
monthNumberPicker.setValue(month);
dayNumberPicker.setValue(day);
}
#Override
protected Parcelable onSaveInstanceState() {
// begin boilerplate code that allows parent classes to save state
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
// end
ss.datetime = this.getDisplayDate().getTime();
return ss;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
// begin boilerplate code so parent classes can restore state
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
// end
setDisplayDate(new Date(ss.datetime));
}
static class SavedState extends BaseSavedState {
long datetime;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
this.datetime = in.readLong();
}
#Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeLong(this.datetime);
}
// required field that makes Parcelables from a Parcel
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
#Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
#Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
It's simple.
Make pCal final, if you don't have to change its value during execution.
OR
Make pCal a class variable if you don't have any problems with a wider scope.
Declare pCal variable as final and initialise persianDatePicker view using findViewById().
You can change the code like this,
btnCheckFalAction = (Button) rootView.findViewById(R.id.btnCheckFal);
persianDatePicker = (PersianDatePicker) rootView.findViewById(R.id.persianDatePicker);
PersianCalendar pCal = persianDatePicker.getDisplayPersianDate();
and also edit your xml like this,
<ir.smartlab.persindatepicker.PersianDatePicker
android:id="#+id/persianDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
I am learning Android from one of the examples in a book (Android Programming - The Big Nerd Ranch Guide) and I am following their code verbatim. Very simple code, well at least I thought...Below is the image of my emulator and most, if not all the code, with the exception of the layout files.
My emulator is using API Level 18 android 4.3.1 cpu ARM. When I click on a crime from the list, I am suppose to see a log stating I clicked on crime #x but I don't see it. Instead I see SoundPool tag with error loading /system/media/audio/ui/KeypressDelete.ogg and 4 other similar errors like error loading KeypressReturn.ogg.
I scoured the internet and on stack overflow for a solution for hours. All I can find is "ignore it" or "turn off the settings", which I don't know how but I don't want to turn it off. I want to solve it and move on with this example so I can learn. Would anyone know of this error and can help me solve it, please? I appreciate it.
Here are part of the code:
public class Crime
{
private UUID mId;
private String mTitle;
private Date mDate;
private boolean mSolved;
public Crime()
{
// Generate unique identifier
mId = UUID.randomUUID();
mDate = new Date();
}
public String getTitle()
{
return mTitle;
}
public void setTitle(String title)
{
mTitle = title;
}
public UUID getId()
{
return mId;
}
public Date getDate()
{
return mDate;
}
public void setDate(Date date)
{
mDate = date;
}
public boolean isSolved()
{
return mSolved;
}
public void setSolved(boolean solved)
{
mSolved = solved;
}
#Override
public String toString()
{
return mTitle;
}
}
public class CrimeLab
{
private ArrayList<Crime> mCrimes;
private static CrimeLab sCrimeLab;
private Context mAppContext;
private CrimeLab(Context appContext)
{
mAppContext = appContext;
mCrimes = new ArrayList<Crime>();
// Mock Crime objects
for (int i = 0; i < 100; i++)
{
Crime c = new Crime();
c.setTitle("Crime #" + i);
c.setSolved(i % 2 == 0); // Every other one
mCrimes.add(c);
}
}
public static CrimeLab get(Context c)
{
if (sCrimeLab == null)
{
sCrimeLab = new CrimeLab(c.getApplicationContext());
}
return sCrimeLab;
}
public ArrayList<Crime> getCrimes()
{
return mCrimes;
}
public Crime getCrime(UUID id)
{
for (Crime c : mCrimes)
{
if (c.getId().equals(id))
return c;
}
return null;
}
}
package com.bignerdranch.android.criminalintent;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class CrimeListFragment extends ListFragment
{
private static final String TAG = "CrimeListFragment";
private ArrayList<Crime> mCrimes;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getActivity().setTitle(R.string.crimes_title);
mCrimes = CrimeLab.get(getActivity()).getCrimes();
ArrayAdapter<Crime> adapter = new ArrayAdapter<Crime>(getActivity(), android.R.layout.simple_list_item_1, mCrimes);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Crime c = (Crime) (getListAdapter()).getItem(position);
Log.d(TAG, c.getTitle() + " was clicked");
}
}
I've just read all questions about this problem at stackoverflow and some forums, but still have no solution. I tried to remove R.java, clear the cache, edit .xml but nothing helps.
Error text:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.easyten.app/com.easyten.app.EasyTenActivity}:
java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to com.slidingmenu.lib.SlidingMenu ...
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to com.slidingmenu.lib.SlidingMenu
at com.slidingmenu.lib.app.SlidingActivityHelper.onCreate(SlidingActivityHelper.java:32)
This is the code:
slidingmenumain.xml
<?xml version="1.0" encoding="utf-8"?>
<com.slidingmenu.lib.SlidingMenu xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/slidingmenumain"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
SlidingActivityHelper.java
package com.slidingmenu.lib.app;
import android.app.Activity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import com.slidingmenu.lib.R;
import com.slidingmenu.lib.SlidingMenu;
public class SlidingActivityHelper {
private Activity mActivity;
private SlidingMenu mSlidingMenu;
private View mViewAbove;
private View mViewBehind;
private boolean mBroadcasting = false;
private boolean mOnPostCreateCalled = false;
private boolean mEnableSlide = true;
public SlidingActivityHelper(Activity activity) {
mActivity = activity;
}
public void onCreate(Bundle savedInstanceState) {
mSlidingMenu = (SlidingMenu) LayoutInflater.from(mActivity).inflate(R.layout.slidingmenumain, null);
}
...other code
}
32 line of SlidingActivityHelper.java is mSlidingMenu = (SlidingMenu) LayoutInflater.from(mActivity).inflate(R.layout.slidingmenumain, null);
SlidingMenu.java
package com.slidingmenu.lib;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import com.slidingmenu.lib.CustomViewAbove.OnPageChangeListener;
public class SlidingMenu extends RelativeLayout {
public static final int TOUCHMODE_MARGIN = 0;
public static final int TOUCHMODE_FULLSCREEN = 1;
private CustomViewAbove mViewAbove;
private CustomViewBehind mViewBehind;
private OnOpenListener mOpenListener;
private OnCloseListener mCloseListener;
//private boolean mSlidingEnabled;
public static void attachSlidingMenu(Activity activity, SlidingMenu sm, boolean slidingTitle) {
if (sm.getParent() != null)
throw new IllegalStateException("SlidingMenu cannot be attached to another view when" +
" calling the static method attachSlidingMenu");
if (slidingTitle) {
// get the window background
TypedArray a = activity.getTheme().obtainStyledAttributes(new int[] {android.R.attr.windowBackground});
int background = a.getResourceId(0, 0);
// move everything into the SlidingMenu
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
decor.removeAllViews();
// save ActionBar themes that have transparent assets
decorChild.setBackgroundResource(background);
sm.setContent(decorChild);
decor.addView(sm);
} else {
// take the above view out of
ViewGroup content = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT);
View above = content.getChildAt(0);
content.removeAllViews();
sm.setContent(above);
content.addView(sm, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
}
public interface OnOpenListener {
public void onOpen();
}
public interface OnOpenedListener {
public void onOpened();
}
public interface OnCloseListener {
public void onClose();
}
public interface OnClosedListener {
public void onClosed();
}
public interface CanvasTransformer {
public void transformCanvas(Canvas canvas, float percentOpen);
}
public SlidingMenu(Context context) {
this(context, null);
}
public SlidingMenu(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingMenu(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutParams behindParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mViewBehind = new CustomViewBehind(context);
addView(mViewBehind, behindParams);
LayoutParams aboveParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mViewAbove = new CustomViewAbove(context);
addView(mViewAbove, aboveParams);
// register the CustomViewBehind2 with the CustomViewAbove
mViewAbove.setCustomViewBehind(mViewBehind);
mViewBehind.setCustomViewAbove(mViewAbove);
mViewAbove.setOnPageChangeListener(new OnPageChangeListener() {
public static final int POSITION_OPEN = 0;
public static final int POSITION_CLOSE = 1;
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) { }
public void onPageSelected(int position) {
if (position == POSITION_OPEN && mOpenListener != null) {
mOpenListener.onOpen();
} else if (position == POSITION_CLOSE && mCloseListener != null) {
mCloseListener.onClose();
}
}
});
// now style everything!
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingMenu);
// set the above and behind views if defined in xml
int viewAbove = ta.getResourceId(R.styleable.SlidingMenu_viewAbove, -1);
if (viewAbove != -1)
setContent(viewAbove);
int viewBehind = ta.getResourceId(R.styleable.SlidingMenu_viewBehind, -1);
if (viewBehind != -1)
setMenu(viewBehind);
int touchModeAbove = ta.getInt(R.styleable.SlidingMenu_aboveTouchMode, TOUCHMODE_MARGIN);
setTouchModeAbove(touchModeAbove);
int touchModeBehind = ta.getInt(R.styleable.SlidingMenu_behindTouchMode, TOUCHMODE_MARGIN);
setTouchModeBehind(touchModeBehind);
int offsetBehind = (int) ta.getDimension(R.styleable.SlidingMenu_behindOffset, -1);
int widthBehind = (int) ta.getDimension(R.styleable.SlidingMenu_behindWidth, -1);
if (offsetBehind != -1 && widthBehind != -1)
throw new IllegalStateException("Cannot set both behindOffset and behindWidth for a SlidingMenu");
else if (offsetBehind != -1)
setBehindOffset(offsetBehind);
else if (widthBehind != -1)
setBehindWidth(widthBehind);
else
setBehindOffset(0);
float scrollOffsetBehind = ta.getFloat(R.styleable.SlidingMenu_behindScrollScale, 0.33f);
setBehindScrollScale(scrollOffsetBehind);
int shadowRes = ta.getResourceId(R.styleable.SlidingMenu_shadowDrawable, -1);
if (shadowRes != -1) {
setShadowDrawable(shadowRes);
}
int shadowWidth = (int) ta.getDimension(R.styleable.SlidingMenu_shadowWidth, 0);
setShadowWidth(shadowWidth);
boolean fadeEnabled = ta.getBoolean(R.styleable.SlidingMenu_behindFadeEnabled, true);
setFadeEnabled(fadeEnabled);
float fadeDeg = ta.getFloat(R.styleable.SlidingMenu_behindFadeDegree, 0.66f);
setFadeDegree(fadeDeg);
boolean selectorEnabled = ta.getBoolean(R.styleable.SlidingMenu_selectorEnabled, false);
setSelectorEnabled(selectorEnabled);
int selectorRes = ta.getResourceId(R.styleable.SlidingMenu_selectorDrawable, -1);
if (selectorRes != -1)
setSelectorDrawable(selectorRes);
}
public void setContent(int res) {
setContent(LayoutInflater.from(getContext()).inflate(res, null));
}
public void setContent(View v) {
mViewAbove.setContent(v);
mViewAbove.invalidate();
showAbove(true);
}
public void setMenu(int res) {
setMenu(LayoutInflater.from(getContext()).inflate(res, null));
}
public void setMenu(View v) {
mViewBehind.setMenu(v);
mViewBehind.invalidate();
}
public void setSlidingEnabled(boolean b) {
mViewAbove.setSlidingEnabled(b);
}
public boolean isSlidingEnabled() {
return mViewAbove.isSlidingEnabled();
}
/**
*
* #param b Whether or not the SlidingMenu is in a static mode
* (i.e. nothing is moving and everything is showing)
*/
public void setStatic(boolean b) {
if (b) {
setSlidingEnabled(false);
mViewAbove.setCustomViewBehind(null);
mViewAbove.setCurrentItem(1);
mViewBehind.setCurrentItem(0);
} else {
mViewAbove.setCurrentItem(1);
mViewBehind.setCurrentItem(1);
mViewAbove.setCustomViewBehind(mViewBehind);
setSlidingEnabled(true);
}
}
/**
* Shows the behind view
*/
public void showBehind(boolean b) {
mViewAbove.setCurrentItem(0, b);
}
public void showBehind() {
mViewAbove.setCurrentItem(0);
}
/**
* Shows the above view
*/
public void showAbove(boolean b) {
mViewAbove.setCurrentItem(1, b);
}
public void showAbove() {
mViewAbove.setCurrentItem(1);
}
/**
*
* #return Whether or not the behind view is showing
*/
public boolean isBehindShowing() {
return mViewAbove.getCurrentItem() == 0;
}
/**
*
* #return The margin on the right of the screen that the behind view scrolls to
*/
public int getBehindOffset() {
return ((RelativeLayout.LayoutParams)mViewBehind.getLayoutParams()).rightMargin;
}
/**
*
* #param i The margin on the right of the screen that the behind view scrolls to
*/
public void setBehindOffset(int i) {
RelativeLayout.LayoutParams params = ((RelativeLayout.LayoutParams)mViewBehind.getLayoutParams());
int bottom = params.bottomMargin;
int top = params.topMargin;
int left = params.leftMargin;
params.setMargins(left, top, i, bottom);
}
/**
*
* #param i The width the Sliding Menu will open to in pixels
*/
#SuppressWarnings("deprecation")
public void setBehindWidth(int i) {
int width;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
try {
Class<?> cls = Display.class;
Class<?>[] parameterTypes = {Point.class};
Point parameter = new Point();
Method method = cls.getMethod("getSize", parameterTypes);
method.invoke(display, parameter);
width = parameter.x;
} catch (Exception e) {
width = display.getWidth();
}
setBehindOffset(width-i);
}
/**
*
* #param res A resource ID which points to the width the Sliding Menu will open to
*/
public void setBehindWidthRes(int res) {
int i = (int) getContext().getResources().getDimension(res);
setBehindWidth(i);
}
/**
*
* #param res The dimension resource to be set as the behind offset
*/
public void setBehindOffsetRes(int res) {
int i = (int) getContext().getResources().getDimension(res);
setBehindOffset(i);
}
/**
*
* #return The scale of the parallax scroll
*/
public float getBehindScrollScale() {
return mViewAbove.getScrollScale();
}
/**
*
* #param f The scale of the parallax scroll (i.e. 1.0f scrolls 1 pixel for every
* 1 pixel that the above view scrolls and 0.0f scrolls 0 pixels)
*/
public void setBehindScrollScale(float f) {
mViewAbove.setScrollScale(f);
}
public void setBehindCanvasTransformer(CanvasTransformer t) {
mViewBehind.setCanvasTransformer(t);
}
public int getTouchModeAbove() {
return mViewAbove.getTouchMode();
}
public void setTouchModeAbove(int i) {
if (i != TOUCHMODE_FULLSCREEN && i != TOUCHMODE_MARGIN) {
throw new IllegalStateException("TouchMode must be set to either" +
"TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN.");
}
mViewAbove.setTouchMode(i);
}
public int getTouchModeBehind() {
return mViewBehind.getTouchMode();
}
public void setTouchModeBehind(int i) {
if (i != TOUCHMODE_FULLSCREEN && i != TOUCHMODE_MARGIN) {
throw new IllegalStateException("TouchMode must be set to either" +
"TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN.");
}
mViewBehind.setTouchMode(i);
}
public void setShadowDrawable(int resId) {
mViewAbove.setShadowDrawable(resId);
}
public void setShadowWidthRes(int resId) {
setShadowWidth((int)getResources().getDimension(resId));
}
public void setShadowWidth(int pixels) {
mViewAbove.setShadowWidth(pixels);
}
public void setFadeEnabled(boolean b) {
mViewAbove.setBehindFadeEnabled(b);
}
public void setFadeDegree(float f) {
mViewAbove.setBehindFadeDegree(f);
}
public void setSelectorEnabled(boolean b) {
mViewAbove.setSelectorEnabled(true);
}
public void setSelectedView(View v) {
mViewAbove.setSelectedView(v);
}
public void setSelectorDrawable(int res) {
mViewAbove.setSelectorDrawable(BitmapFactory.decodeResource(getResources(), res));
}
public void setSelectorDrawable(Bitmap b) {
mViewAbove.setSelectorDrawable(b);
}
public void setOnOpenListener(OnOpenListener listener) {
//mViewAbove.setOnOpenListener(listener);
mOpenListener = listener;
}
public void setOnCloseListener(OnCloseListener listener) {
//mViewAbove.setOnCloseListener(listener);
mCloseListener = listener;
}
public void setOnOpenedListener(OnOpenedListener listener) {
mViewAbove.setOnOpenedListener(listener);
}
public void setOnClosedListener(OnClosedListener listener) {
mViewAbove.setOnClosedListener(listener);
}
private static class SavedState extends BaseSavedState {
boolean mBehindShowing;
public SavedState(Parcelable superState) {
super(superState);
}
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeBooleanArray(new boolean[]{mBehindShowing});
}
/*
public static final Parcelable.Creator<SavedState> CREATOR
= ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() {
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
});
SavedState(Parcel in) {
super(in);
boolean[] showing = new boolean[1];
in.readBooleanArray(showing);
mBehindShowing = showing[0];
}
*/
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.mBehindShowing = isBehindShowing();
return ss;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
if (ss.mBehindShowing) {
showBehind(true);
} else {
showAbove(true);
}
}
#Override
protected boolean fitSystemWindows(Rect insets) {
int leftPadding = getPaddingLeft() + insets.left;
int rightPadding = getPaddingRight() + insets.right;
int topPadding = insets.top;
int bottomPadding = insets.bottom;
this.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
return super.fitSystemWindows(insets);
}
}
What's wrong? How can I fix it? I'm using IntelliJ IDEA 12 CE. Thanks a lot for any help!
This can be resolved by recreating the R.java file.
1. Re-build OR
2. Change the 'android:id' in XML file to a new id and re-build. Make sure you manually change all references to this id.
Sometimes this does´t work even recreating the R.java file, cleaning and rebuilding the project.
for me it works until i delete \gen and \bin folders, then automatically were recreated with the new relationship between resources and their id´s.
I think the problem is just that the inflater cast your item to RelativeLayout and you can't cast a relativeLayout in your item (Maybe this post is more precise : ClassCastException). Perhaps you have to give up and retrieve your object using your id with findViewById.