Update or Override File in Android Support Library - java

I have discovered what I think is a bug in FragmentTabHost.java which always generates a new layout for the tabhost even if a layout is specified. See the google discussion here.
I want to override this file in my project, but I encountered errors when I imported it into my project.
Does anyone know the right way to use my own copy of FragmentTabHost.java?

you can use this class, then extend your new class with this
public class YourFragmentTabHost extends FragmentTabHost {
FragmentTabHost.java
import java.util.ArrayList;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
public class FragmentTabHost extends TabHost
implements TabHost.OnTabChangeListener {
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private FrameLayout mRealTabContent;
private Context mContext;
private FragmentManager mFragmentManager;
private int mContainerId;
private TabHost.OnTabChangeListener mOnTabChangeListener;
private TabInfo mLastTab;
private boolean mAttached;
static final class TabInfo {
private final String tag;
private final Class<?> clss;
private final Bundle args;
private Fragment fragment;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
static class SavedState extends BaseSavedState {
String curTab;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
curTab = in.readString();
}
#Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeString(curTab);
}
#Override
public String toString() {
return "FragmentTabHost.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " curTab=" + curTab + "}";
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
public FragmentTabHost(Context context) {
// Note that we call through to the version that takes an AttributeSet,
// because the simple Context construct can result in a broken object!
super(context, null);
initFragmentTabHost(context, null);
}
public FragmentTabHost(Context context, AttributeSet attrs) {
super(context, attrs);
initFragmentTabHost(context, attrs);
}
private void initFragmentTabHost(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs,
new int[] { android.R.attr.inflatedId }, 0, 0);
mContainerId = a.getResourceId(0, 0);
a.recycle();
super.setOnTabChangedListener(this);
}
/**
* #deprecated Don't call the original TabHost setup, you must instead
* call {#link #setup(Context, FragmentManager)} or
* {#link #setup(Context, FragmentManager, int)}.
*/
#Override #Deprecated
public void setup() {
throw new IllegalStateException(
"Must call setup() that takes a Context and FragmentManager");
}
public void setup(Context context, FragmentManager manager) {
super.setup();
mContext = context;
mFragmentManager = manager;
ensureContent();
}
public void setup(Context context, FragmentManager manager, int containerId) {
super.setup();
mContext = context;
mFragmentManager = manager;
mContainerId = containerId;
ensureContent();
mRealTabContent.setId(containerId);
// We must have an ID to be able to save/restore our state. If
// the owner hasn't set one at this point, we will set it ourself.
if (getId() == View.NO_ID) {
setId(android.R.id.tabhost);
}
}
private void ensureContent() {
if (mRealTabContent == null) {
mRealTabContent = (FrameLayout)findViewById(mContainerId);
if (mRealTabContent == null) {
throw new IllegalStateException(
"No tab content FrameLayout found for id " + mContainerId);
}
}
}
#Override
public void setOnTabChangedListener(OnTabChangeListener l) {
mOnTabChangeListener = l;
}
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
if (mAttached) {
// If we are already attached to the window, then check to make
// sure this tab's fragment is inactive if it exists. This shouldn't
// normally happen.
info.fragment = mFragmentManager.findFragmentByTag(tag);
if (info.fragment != null && !info.fragment.isDetached()) {
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.detach(info.fragment);
ft.commit();
}
}
mTabs.add(info);
addTab(tabSpec);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
String currentTab = getCurrentTabTag();
// Go through all tabs and make sure their fragments match
// the correct state.
FragmentTransaction ft = null;
for (int i=0; i<mTabs.size(); i++) {
TabInfo tab = mTabs.get(i);
tab.fragment = mFragmentManager.findFragmentByTag(tab.tag);
if (tab.fragment != null && !tab.fragment.isDetached()) {
if (tab.tag.equals(currentTab)) {
// The fragment for this tab is already there and
// active, and it is what we really want to have
// as the current tab. Nothing to do.
mLastTab = tab;
} else {
// This fragment was restored in the active state,
// but is not the current tab. Deactivate it.
if (ft == null) {
ft = mFragmentManager.beginTransaction();
}
ft.detach(tab.fragment);
}
}
}
// We are now ready to go. Make sure we are switched to the
// correct tab.
mAttached = true;
ft = doTabChanged(currentTab, ft);
if (ft != null) {
ft.commit();
mFragmentManager.executePendingTransactions();
}
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mAttached = false;
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.curTab = getCurrentTabTag();
return ss;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
setCurrentTabByTag(ss.curTab);
}
#Override
public void onTabChanged(String tabId) {
if (mAttached) {
android.support.v4.app.FragmentTransaction ft = doTabChanged(tabId, null);
if (ft != null) {
ft.commit();
}
}
if (mOnTabChangeListener != null) {
mOnTabChangeListener.onTabChanged(tabId);
}
}
private FragmentTransaction doTabChanged(String tabId, android.support.v4.app.FragmentTransaction ft) {
TabInfo newTab = null;
for (int i=0; i<mTabs.size(); i++) {
TabInfo tab = mTabs.get(i);
if (tab.tag.equals(tabId)) {
newTab = tab;
}
}
if (newTab == null) {
throw new IllegalStateException("No tab known for tag " + tabId);
}
if (mLastTab != newTab) {
if (ft == null) {
ft = mFragmentManager.beginTransaction();
}
if (mLastTab != null) {
if (mLastTab.fragment != null) {
ft.detach(mLastTab.fragment);
}
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(mContext,
newTab.clss.getName(), newTab.args);
ft.add(mContainerId, newTab.fragment, newTab.tag);
} else {
ft.attach(newTab.fragment);
}
}
mLastTab = newTab;
}
return ft;
}
}

Related

Having issue in custom adapter listview

import org.alljoyn.bus.sample.chat.ChatApplication;
import org.alljoyn.bus.sample.chat.Observable;
import org.alljoyn.bus.sample.chat.Observer;
import org.alljoyn.bus.sample.chat.DialogBuilder;
import java.lang.reflect.Array;
// ... more imports
public class UseActivity extends Activity implements Observer {
private static final String TAG = "chat.UseActivity";
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.use);
ListView hlv = (ListView) findViewById(R.id.useHistoryList);
hlv.setAdapter(mHistoryList);
EditText messageBox = (EditText)findViewById(R.id.useMessage);
messageBox.setSingleLine();
messageBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
message = view.getText().toString();
Log.i(TAG, "useMessage.onEditorAction(): got message " + message + ")");
mHistoryList.add(message);
mChatApplication.newLocalUserMessage(message);
view.setText("");
}
return true;
}
});
Button mAlertButton = (Button)findViewById(R.id.alert);
mAlertButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
message = "www.google.com" ;
mHistoryList.add(message);
mChatApplication.newLocalUserMessage(message);
}
});
mJoinButton = (Button)findViewById(R.id.useJoin);
mJoinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_JOIN_ID);
}
});
mLeaveButton = (Button)findViewById(R.id.useLeave);
mLeaveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_LEAVE_ID);
}
});
mChannelName = (TextView)findViewById(R.id.useChannelName);
mChannelStatus = (TextView)findViewById(R.id.useChannelStatus);
/*
* Keep a pointer to the Android Application class around. We use this
* as the Model for our MVC-based application. Whenever we are started
* we need to "check in" with the application so it can ensure that our
* required services are running.
*/
mChatApplication = (ChatApplication)getApplication();
mChatApplication.checkin();
/*
* Call down into the model to get its current state. Since the model
* outlives its Activities, this may actually be a lot of state and not
* just empty.
*/
updateChannelState();
updateHistory();
/*
* Now that we're all ready to go, we are ready to accept notifications
* from other components.
*/
mChatApplication.addObserver(this);
}
public void onDestroy() {
Log.i(TAG, "onDestroy()");
mChatApplication = (ChatApplication)getApplication();
mChatApplication.deleteObserver(this);
super.onDestroy();
}
public static final int DIALOG_JOIN_ID = 0;
public static final int DIALOG_LEAVE_ID = 1;
public static final int DIALOG_ALLJOYN_ERROR_ID = 2;
protected Dialog onCreateDialog(int id) {
Log.i(TAG, "onCreateDialog()");
Dialog result = null;
switch(id) {
case DIALOG_JOIN_ID:
{
DialogBuilder builder = new DialogBuilder();
result = builder.createUseJoinDialog(this, mChatApplication);
}
break;
case DIALOG_LEAVE_ID:
{
DialogBuilder builder = new DialogBuilder();
result = builder.createUseLeaveDialog(this, mChatApplication);
}
break;
case DIALOG_ALLJOYN_ERROR_ID:
{
DialogBuilder builder = new DialogBuilder();
result = builder.createAllJoynErrorDialog(this, mChatApplication);
}
break;
}
return result;
}
public synchronized void update(Observable o, Object arg) {
Log.i(TAG, "update(" + arg + ")");
String qualifier = (String)arg;
if (qualifier.equals(ChatApplication.APPLICATION_QUIT_EVENT)) {
Message message = mHandler.obtainMessage(HANDLE_APPLICATION_QUIT_EVENT);
mHandler.sendMessage(message);
}
if (qualifier.equals(ChatApplication.HISTORY_CHANGED_EVENT)) {
Message message = mHandler.obtainMessage(HANDLE_HISTORY_CHANGED_EVENT);
mHandler.sendMessage(message);
}
if (qualifier.equals(ChatApplication.USE_CHANNEL_STATE_CHANGED_EVENT)) {
Message message = mHandler.obtainMessage(HANDLE_CHANNEL_STATE_CHANGED_EVENT);
mHandler.sendMessage(message);
}
if (qualifier.equals(ChatApplication.ALLJOYN_ERROR_EVENT)) {
Message message = mHandler.obtainMessage(HANDLE_ALLJOYN_ERROR_EVENT);
mHandler.sendMessage(message);
}
}
private void updateHistory() {
Log.i(TAG, "updateHistory()");
List <String> messages = mChatApplication.getHistory();
mHistoryList = new SimpleAdapter (this, messages);
for (String message : messages) {
mHistoryList.add(message);
}
mHistoryList.notifyDataSetChanged();
}
private void updateChannelState() {
Log.i(TAG, "updateHistory()");
AllJoynService.UseChannelState channelState = mChatApplication.useGetChannelState();
String name = mChatApplication.useGetChannelName();
if (name == null) {
name = "Not set";
}
mChannelName.setText(name);
switch (channelState) {
case IDLE:
mChannelStatus.setText("Idle");
mJoinButton.setEnabled(true);
mLeaveButton.setEnabled(false);
break;
case JOINED:
mChannelStatus.setText("Joined");
mJoinButton.setEnabled(false);
mLeaveButton.setEnabled(true);
break;
}
}
/**
* An AllJoyn error has happened. Since this activity pops up first we
* handle the general errors. We also handle our own errors.
*/
private void alljoynError() {
if (mChatApplication.getErrorModule() == ChatApplication.Module.GENERAL ||
mChatApplication.getErrorModule() == ChatApplication.Module.USE) {
showDialog(DIALOG_ALLJOYN_ERROR_ID);
}
}
private static final int HANDLE_APPLICATION_QUIT_EVENT = 0;
private static final int HANDLE_HISTORY_CHANGED_EVENT = 1;
private static final int HANDLE_CHANNEL_STATE_CHANGED_EVENT = 2;
private static final int HANDLE_ALLJOYN_ERROR_EVENT = 3;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLE_APPLICATION_QUIT_EVENT:
{
Log.i(TAG, "mHandler.handleMessage(): HANDLE_APPLICATION_QUIT_EVENT");
finish();
}
break;
case HANDLE_HISTORY_CHANGED_EVENT:
{
Log.i(TAG, "mHandler.handleMessage(): HANDLE_HISTORY_CHANGED_EVENT");
updateHistory();
break;
}
case HANDLE_CHANNEL_STATE_CHANGED_EVENT:
{
Log.i(TAG, "mHandler.handleMessage(): HANDLE_CHANNEL_STATE_CHANGED_EVENT");
updateChannelState();
break;
}
case HANDLE_ALLJOYN_ERROR_EVENT:
{
Log.i(TAG, "mHandler.handleMessage(): HANDLE_ALLJOYN_ERROR_EVENT");
alljoynError();
break;
}
default:
break;
}
}
};
private ChatApplication mChatApplication = null;
String message;
private SimpleAdapter mHistoryList;
private Button mJoinButton;
private Button mLeaveButton;
private TextView mChannelName;
private TextView mChannelStatus;
}
I'm having some troubles getting my custom listView adapter to work. I am having issue in getting the message values dynamically into the custom adapter. I have got the values dynamically but when I used that in my code, the app crashes or it displays nothing.
import android.text.util.Linkify;
// ... more imports
public class SimpleAdapter extends ArrayAdapter<String> {
private final Context context;
private final List<String> values;
public SimpleAdapter(Context context, List <String> values) {
super(context, -1, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.view, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.text);
textView.setText(values.get(position));
Linkify.addLinks(textView,Linkify.WEB_URLS);
return rowView;
}
}

How to detect if it is Recents button, Multi Window mode or home button onUserLeaveHint()

In my app, I am relying on onUserLeaveHint() method when the user presses the home button, but this method is also being called when you are starting multi window mode in android 7.0 by long pressing "recents button" (which I don't want to perform same thing that I do when home button been pressed). So I want to know if there is a way to detect which is which. Cheers!
Note: onMultiWindowModeChanged() being called after onUserLeaveHint()
I think this is what you're looking for.
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
// do something here...
}
#Override
public void onHomeLongPressed() {
}
});
mHomeWatcher.startWatch();
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_LONG_PRESS = "assist";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_LONG_PRESS)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
public interface OnHomePressedListener {
public void onHomePressed();
public void onHomeLongPressed();
}

how to call onOptionsItemSelected on a different activity

I have an activity with uses onOptionsItemSelected(MenuItem item) method in FolderActivity and I want to call this method on another activity (MainActivity)
the main activity uses CMU Sphinx - Speech Recognition Toolkit.
I need to call some methods from FolderActivity to MainActivity.
package com.evolution.filemanager.folders;
import static android.widget.Toast.makeText;
import java.io.File;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.evolution.filemanager.FileManagerApplication;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.clipboard.Clipboard;
import com.evolution.filemanager.clipboard.Clipboard.ClipboardListener;
import com.evolution.filemanager.clipboard.ClipboardFileAdapter;
import com.evolution.filemanager.favourites.FavouritesManager;
import com.evolution.filemanager.favourites.FavouritesManager.FavouritesListener;
import com.evolution.filemanager.nav_drawer.NavDrawerAdapter;
import com.evolution.utils.FontApplicator;
import com.evolution.utils.ListViewUtils;
import edu.cmu.pocketsphinx.demo.R;
public class FolderActivity extends Activity implements OnItemClickListener, ClipboardListener, FavouritesListener
{
public static class FolderNotOpenException extends Exception
{
}
private static final String LOG_TAG = "Main Activity";
public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
File lastFolder=null;
private FontApplicator fontApplicator;
public static Activity FOLDERACTIVITY;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_folder);
setupDrawers();
Clipboard.getInstance().addListener(this);
FOLDERACTIVITY = this;
fontApplicator = new FontApplicator(getApplicationContext(), "Roboto_Light.ttf").applyFont(getWindow().getDecorView());
}
public FontApplicator getFontApplicator()
{
return fontApplicator;
}
#Override
protected void onDestroy()
{
Clipboard.getInstance().removeListener(this);
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getFavouritesManager().removeFavouritesListener(this);
super.onDestroy();
}
public void setLastFolder(File lastFolder)
{
this.lastFolder = lastFolder;
}
#Override
protected void onPause()
{
if (lastFolder != null)
{
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
}
super.onPause();
}
public void setActionbarVisible(boolean visible)
{
ActionBar actionBar = getActionBar();
if (actionBar == null) return;
if (visible)
{
actionBar.show();
setSystemBarTranslucency(false);
}
else
{
actionBar.hide();
setSystemBarTranslucency(true);
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
protected void setSystemBarTranslucency(boolean translucent)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
if (translucent)
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
else
{
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags &= (~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setAttributes(params);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
public void setupDrawers()
{
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
{
boolean actionBarShown = false;
#Override
public void onDrawerOpened(View drawerView)
{
makeText(getApplicationContext(), "drawer open", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(drawerView);
setActionbarVisible(true);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView)
{
makeText(getApplicationContext(), "drawer close", Toast.LENGTH_SHORT).show();
actionBarShown=false;
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0 && actionBarShown == false)
{
actionBarShown = true;
setActionbarVisible(true);
}
else if (slideOffset <= 0) actionBarShown = false;
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
drawerLayout.setFocusableInTouchMode(false);
// drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setupNavDrawer();
setupClipboardDrawer();
}
#Override
public void onBackPressed()
{
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else if (drawerLayout.isDrawerOpen(GravityCompat.END))
drawerLayout.closeDrawer(GravityCompat.END);
else
super.onBackPressed();
}
void setupNavDrawer()
{
FileManagerApplication application = (FileManagerApplication) getApplication();
// add listview header to push items below the actionbar
ListView navListView = (ListView) findViewById(R.id.listNavigation);
ListViewUtils.addListViewPadding(navListView, this, true);
loadFavourites(application.getFavouritesManager());
application.getFavouritesManager().addFavouritesListener(this);
}
void setupClipboardDrawer()
{
// add listview header to push items below the actionbar
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
ListViewUtils.addListViewHeader(clipboardListView, this);
onClipboardContentsChange(Clipboard.getInstance());
}
void loadFavourites(FavouritesManager favouritesManager)
{
ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
NavDrawerAdapter navDrawerAdapter = new NavDrawerAdapter(this, new ArrayList<NavDrawerAdapter.NavDrawerItem>(favouritesManager.getFolders()));
navDrawerAdapter.setFontApplicator(fontApplicator);
listNavigation.setAdapter(navDrawerAdapter);
listNavigation.setOnItemClickListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
if (getFragmentManager().findFragmentById(R.id.fragment) == null)
{
FolderFragment folderFragment = new FolderFragment();
if (getIntent().hasExtra(EXTRA_DIR))
{
Bundle args = new Bundle();
args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
folderFragment.setArguments(args);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, folderFragment)
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
makeText(getApplicationContext(), "unsa ni?", Toast.LENGTH_SHORT).show();
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
if (actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId())
{
case R.id.menu_about:
startActivity(new Intent(getApplicationContext(), AboutActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFragment(Fragment fragment)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment, fragment)
.commit();
}
public void goBack()
{
getFragmentManager().popBackStack();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public FolderFragment getFolderFragment()
{
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment);
if (fragment instanceof FolderFragment)
return (FolderFragment) fragment;
else return null;
}
public File getCurrentFolder() throws FolderNotOpenException
{
FolderFragment folderFragment = getFolderFragment();
if (folderFragment == null)
throw new FolderNotOpenException();
else return folderFragment.currentDir;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch (arg0.getId())
{
case R.id.listNavigation:
NavDrawerAdapter.NavDrawerItem item = (NavDrawerAdapter.NavDrawerItem) arg0.getItemAtPosition(arg2);
if (item.onClicked(this))
drawerLayout.closeDrawers();
break;
case R.id.listClipboard:
FolderFragment folderFragment = getFolderFragment();
if (folderFragment != null)
{
// TODO: paste single file
}
break;
default:
break;
}
}
public File getLastFolder()
{
return lastFolder;
}
#Override
public void onClipboardContentsChange(Clipboard clipboard)
{
invalidateOptionsMenu();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
if (clipboard.isEmpty() && drawerLayout != null)
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
else
{
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
FileManagerApplication application = (FileManagerApplication) getApplication();
if (clipboardListView != null)
{
ClipboardFileAdapter clipboardFileAdapter = new ClipboardFileAdapter(this, clipboard, application.getFileIconResolver());
clipboardFileAdapter.setFontApplicator(fontApplicator);
clipboardListView.setAdapter(clipboardFileAdapter);
}
}
}
#Override
public void onFavouritesChanged(FavouritesManager favouritesManager)
{
loadFavourites(favouritesManager);
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event)
{
Log.d("Key Long Press", event.toString());
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
return true;
}
else return super.onKeyLongPress(keyCode, event);
}
}
and the activity where I want to call
package edu.cmu.pocketsphinx.demo;
import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.folders.FolderActivity;
import com.evolution.utils.DataClearer;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;
public class MainActivity extends Activity implements
RecognitionListener {
public AnimationDrawable rocketAnimation;
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "digits";
private static final String MENU_SEARCH = "menu";
private static final String KEYPHRASE = "frost";
private static final String GO_BACK = "back";
private static final String PREVIOUS = "previous";
private static final String OPEN_FILE_MANAGER = "open file manager";
private static final String OPEN_ABOUT = "open about";
private static final String OPEN_MUSIC = "open music";
private static final String OPEN_PICTURES = "open pictures";
private static final String OPEN_VIDEOS = "open videos";
private static final String SHOW_COMMANDS = "show commands";
private static final String CLOSE_FILE_MANAGER = "close file manager";
private static final String CLOSE_ABOUT = "close about";
private static final String CLOSE_MUSIC = "close music";
private static final String CLOSE_PICTURES = "close pictures";
private static final String CLOSE_VIDEOS = "close videos";
private static final String CLOSE_COMMANDS = "close commands";
private static final String SHOW_DRAWER = "show drawer";
private static final String HIDE_DRAWER = "hide drawer";
public static boolean isOPEN_FILE_MANAGER = false;
private static boolean isOPEN_ABOUT = false;
private static boolean isOPEN_MUSIC = false;
private static boolean isOPEN_PICTURES = false;
private static boolean isOPEN_VIDEOS = false;
private static boolean isSHOW_COMMANDS = false;
private static boolean isSHOW_DRAWER = false;
private static String MENU_CAPTION;
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Prepare the data for UI
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
captions.put(DIGITS_SEARCH, R.string.digits_caption);
captions.put(FORECAST_SEARCH, R.string.forecast_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
ImageView rocketImage = (ImageView) findViewById(R.id.imageViewAnim);
rocketImage.setBackgroundResource(R.drawable.heart_animation);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
TextView tv = ((TextView) findViewById(R.id.caption_text));
if (text.equals(KEYPHRASE))
{
switchSearch(MENU_SEARCH);
rocketAnimation.start();
}
else if (text.equals(OPEN_FILE_MANAGER))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , FolderActivity.class);
startActivity(intent);
isOPEN_FILE_MANAGER = true;
}
else if (text.equals(CLOSE_FILE_MANAGER))
{
if(isOPEN_FILE_MANAGER == true)
{
switchSearch(KWS_SEARCH);
FolderActivity.FOLDERACTIVITY.finish();
isOPEN_FILE_MANAGER = false;
}
}
else if (text.equals(SHOW_COMMANDS))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , Commands.class);
startActivity(intent);
isSHOW_COMMANDS = true;
}
else if (text.equals(CLOSE_COMMANDS))
{
if(isSHOW_COMMANDS == true)
{
switchSearch(KWS_SEARCH);
Commands.SHOWCOMMANDS.finish();
}
}
else if (text.equals(OPEN_PICTURES))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , AboutActivity.class);
startActivity(intent);
}
else if(text.equals(OPEN_ABOUT))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent(PocketSphinxActivity.this, AboutActivity.class);
startActivity(intent);
isOPEN_ABOUT = true;
}
else if(text.equals(CLOSE_ABOUT))
{
if (isOPEN_ABOUT == true)
{
switchSearch(KWS_SEARCH);
AboutActivity.ABOUTACTIVITY.finish();
}
}
else if(text.equals(GO_BACK) || text.equals(PREVIOUS))
{
if(isOPEN_FILE_MANAGER == true )
{
FolderActivity.FOLDERACTIVITY//where i want to call onOptionsItemSelected
switchSearch(KWS_SEARCH);
}
}
else
{
switchSearch(KWS_SEARCH);
((TextView) findViewById(R.id.result_text)).setText(text);
}
}
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
if (DIGITS_SEARCH.equals(recognizer.getSearchName())
|| FORECAST_SEARCH.equals(recognizer.getSearchName())
|| OPEN_FILE_MANAGER.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create grammar-based searches.
File menuGrammar = new File(modelsDir, "grammar/menu.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this); //clear cache to minimize the app size
DataClearer.getInstance().clearApplicationData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
the FolderActivity runs on top of the MainActivty but the voice recognition in MainActivity is still active and I want the voice itself do some manipulation in the FolderActivity
Here's a few suggestions:
Have FolderActivity register a BroadcastReceiver as a listener for a certain Intent. When MainActivity wants to do something in FolderActivity, it can send a broadcast Intent which will be seen by the BroadcastReceiver in FolderActivity, which can then call the appropriate method in the `Activity.
When MainActivity wants to do something in FolderActivity, it can launch FolderActivity again using an Intent with flag Intent.FLAG_ACTIVITY_SINGLE_TOP and some "extra" that describes what FolderActivity should do. In FolderActivity override onNewIntent(), read the passed Intent parameter and use it to determine what method to call in FolderActivity. Because the Activity was launched withIntent.FLAG_ACTIVITY_SINGLE_TOP, Android won't create a new instance of the Activity, it will just callonNewIntent()` on the existing instance.
Have FolderActivity set a public static variable of type Activity to a reference to itself in onCreate(). MainActivity can then call a method on FolderActivity by doing something like FolderActivity.activityReference.doSomething()
Method 3 is not the preferred method, since you need to make sure that you set the public static variable to null in FolderActivity.onDestroy() and there are other concerns (timing issues, memory leaks, etc.) that need to be dealt with properly.
NOTE: You probably don't want to call onOptionsItemSelected() directly. This method is called by the Android framework when an options item is selected by the user. You should call directly the method that actually does something, not this framework callback method.

Set onclickLister in utube api

i'm using youtubeApi (https://developers.google.com/youtube/android/player/downloads/), I'm looking for a solution for put an onclick listener on the videos on the VideoWall..
package com.android.youbho.Activities;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.PlayerStyle;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.android.youbho.Utils.Constant;
import com.android.youbho.Utils.FlippingView;
import com.android.youbho.Utils.ImageWallView;
#SuppressLint("NewApi") public class VideoWallActivity extends Activity implements
FlippingView.Listener,
YouTubePlayer.OnInitializedListener,
YouTubeThumbnailView.OnInitializedListener{
private static final int RECOVERY_DIALOG_REQUEST = 1;
/** The player view cannot be smaller than 110 pixels high. */
private static final float PLAYER_VIEW_MINIMUM_HEIGHT_DP = 110;
private static final int MAX_NUMBER_OF_ROWS_WANTED = 4;
// Example playlist from which videos are displayed on the video wall
private static final String PLAYLIST_ID = "PLBA95EAD360E2B0D1";
private static final int INTER_IMAGE_PADDING_DP = 5;
// YouTube thumbnails have a 16 / 9 aspect ratio
private static final double THUMBNAIL_ASPECT_RATIO = 16 / 9d;
private static final int INITIAL_FLIP_DURATION_MILLIS = 100;
private static final int FLIP_DURATION_MILLIS = 500;
private static final int FLIP_PERIOD_MILLIS = 2000;
private ImageWallView imageWallView;
private Handler flipDelayHandler;
private FlippingView flippingView;
private YouTubeThumbnailView thumbnailView;
private YouTubeThumbnailLoader thumbnailLoader;
private YouTubePlayerFragment playerFragment;
private View playerView;
private YouTubePlayer player;
private Dialog errorDialog;
private int flippingCol;
private int flippingRow;
private int videoCol;
private int videoRow;
private boolean nextThumbnailLoaded;
private boolean activityResumed;
private State state;
private static final int id_videoPlayer=99;
private enum State {
UNINITIALIZED,
LOADING_THUMBNAILS,
VIDEO_FLIPPED_OUT,
VIDEO_LOADING,
VIDEO_CUED,
VIDEO_PLAYING,
VIDEO_ENDED,
VIDEO_BEING_FLIPPED_OUT,
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Toast.makeText(getApplicationContext(), "lol:" + position, Toast.LENGTH_LONG).show();
return view;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #SuppressLint("NewApi") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
state = State.UNINITIALIZED;
ViewGroup viewFrame = new FrameLayout(this);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int maxAllowedNumberOfRows = (int) Math.floor((displayMetrics.heightPixels / displayMetrics.density) / PLAYER_VIEW_MINIMUM_HEIGHT_DP);
int numberOfRows = Math.min(maxAllowedNumberOfRows, MAX_NUMBER_OF_ROWS_WANTED);
int interImagePaddingPx = (int) displayMetrics.density * INTER_IMAGE_PADDING_DP;
int imageHeight = (displayMetrics.heightPixels / numberOfRows) - interImagePaddingPx;
int imageWidth = (int) (imageHeight * THUMBNAIL_ASPECT_RATIO);
imageWallView = new ImageWallView(this, imageWidth, imageHeight, interImagePaddingPx);
viewFrame.addView(imageWallView, MATCH_PARENT, MATCH_PARENT);
thumbnailView = new YouTubeThumbnailView(this);
thumbnailView.initialize(Constant.DEVELOPER_KEY, this);
flippingView = new FlippingView(this, this, imageWidth, imageHeight);
flippingView.setFlipDuration(INITIAL_FLIP_DURATION_MILLIS);
viewFrame.addView(flippingView, imageWidth, imageHeight);
playerView = new FrameLayout(this);
playerView.setId(id_videoPlayer);
playerView.setVisibility(View.INVISIBLE);
viewFrame.addView(playerView, imageWidth, imageHeight);
playerFragment = YouTubePlayerFragment.newInstance();
playerFragment.initialize(Constant.DEVELOPER_KEY, this);
getFragmentManager().beginTransaction().add(id_videoPlayer, playerFragment).commit();
flipDelayHandler = new FlipDelayHandler();
setContentView(viewFrame);
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView, YouTubeThumbnailLoader thumbnailLoader) {
thumbnailView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "lol! ", Toast.LENGTH_LONG).show();
}
});
this.thumbnailLoader = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailListener());
maybeStartDemo();
}
#Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
if (errorDialog == null || !errorDialog.isShowing()) {
errorDialog = errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST);
errorDialog.show();
}
} else {
String errorMessage = String.format( errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasResumed) {
VideoWallActivity.this.player = player;
player.setPlayerStyle(PlayerStyle.CHROMELESS);
player.setPlayerStateChangeListener(new VideoListener());
maybeStartDemo();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
if (errorDialog == null || !errorDialog.isShowing()) {
errorDialog = errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST);
errorDialog.show();
}
} else {
String errorMessage = String.format( errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
private void maybeStartDemo() {
if (activityResumed && player != null && thumbnailLoader != null && state.equals(State.UNINITIALIZED)) {
thumbnailLoader.setPlaylist(PLAYLIST_ID); // loading the first thumbnail will kick off demo
state = State.LOADING_THUMBNAILS;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
if (errorDialog != null && errorDialog.isShowing()) {
errorDialog.dismiss();
}
errorDialog = null;
playerFragment.initialize(Constant.DEVELOPER_KEY, this);
thumbnailView.initialize(Constant.DEVELOPER_KEY, this);
}
}
#Override
protected void onResume() {
super.onResume();
activityResumed = true;
if (thumbnailLoader != null && player != null) {
if (state.equals(State.UNINITIALIZED)) {
maybeStartDemo();
} else if (state.equals(State.LOADING_THUMBNAILS)) {
loadNextThumbnail();
} else {
if (state.equals(State.VIDEO_PLAYING)) {
player.play();
}
flipDelayHandler.sendEmptyMessageDelayed(0, FLIP_DURATION_MILLIS);
}
}
}
#Override
protected void onPause() {
flipDelayHandler.removeCallbacksAndMessages(null);
activityResumed = false;
super.onPause();
}
#Override
protected void onDestroy() {
if (thumbnailLoader != null) {
thumbnailLoader.release();
}
super.onDestroy();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) private void flipNext() {
if (!nextThumbnailLoaded || state.equals(State.VIDEO_LOADING)) {
return;
}
if (state.equals(State.VIDEO_ENDED)) {
flippingCol = videoCol;
flippingRow = videoRow;
state = State.VIDEO_BEING_FLIPPED_OUT;
} else {
Pair<Integer, Integer> nextTarget = imageWallView.getNextLoadTarget();
flippingCol = nextTarget.first;
flippingRow = nextTarget.second;
}
flippingView.setX(imageWallView.getXPosition(flippingCol, flippingRow));
flippingView.setY(imageWallView.getYPosition(flippingCol, flippingRow));
flippingView.setFlipInDrawable(thumbnailView.getDrawable());
flippingView.setFlipOutDrawable(imageWallView.getImageDrawable(flippingCol, flippingRow));
imageWallView.setImageDrawable(flippingCol, flippingRow, thumbnailView.getDrawable());
imageWallView.hideImage(flippingCol, flippingRow);
flippingView.setVisibility(View.VISIBLE);
flippingView.flip();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onFlipped(FlippingView view) {
imageWallView.showImage(flippingCol, flippingRow);
flippingView.setVisibility(View.INVISIBLE);
if (activityResumed) {
loadNextThumbnail();
if (state.equals(State.VIDEO_BEING_FLIPPED_OUT)) {
state = State.VIDEO_FLIPPED_OUT;
} else if (state.equals(State.VIDEO_CUED)) {
videoCol = flippingCol;
videoRow = flippingRow;
playerView.setX(imageWallView.getXPosition(flippingCol, flippingRow));
playerView.setY(imageWallView.getYPosition(flippingCol, flippingRow));
imageWallView.hideImage(flippingCol, flippingRow);
playerView.setVisibility(View.VISIBLE);
player.play();
state = State.VIDEO_PLAYING;
} else if (state.equals(State.LOADING_THUMBNAILS) && imageWallView.allImagesLoaded()) {
state = State.VIDEO_FLIPPED_OUT; // trigger flip in of an initial video
flippingView.setFlipDuration(FLIP_DURATION_MILLIS);
flipDelayHandler.sendEmptyMessage(0);
}
}
}
private void loadNextThumbnail() {
nextThumbnailLoaded = false;
if (thumbnailLoader.hasNext()) {
thumbnailLoader.next();
} else {
thumbnailLoader.first();
}
}
/**
* A handler that periodically flips an element on the video wall.
*/
#SuppressLint("HandlerLeak")
private final class FlipDelayHandler extends Handler {
#Override
public void handleMessage(Message msg) {
flipNext();
sendEmptyMessageDelayed(0, FLIP_PERIOD_MILLIS);
}
}
/**
* An internal listener which listens to thumbnail loading events from the
* {#link YouTubeThumbnailView}.
*/
private final class ThumbnailListener implements YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView thumbnail, String videoId) {
nextThumbnailLoaded = true;
if (activityResumed) {
if (state.equals(State.LOADING_THUMBNAILS)) {
flipNext();
} else if (state.equals(State.VIDEO_FLIPPED_OUT)) {
// load player with the video of the next thumbnail being flipped in
state = State.VIDEO_LOADING;
player.cueVideo(videoId);
}
}
}
#Override
public void onThumbnailError(YouTubeThumbnailView thumbnail, YouTubeThumbnailLoader.ErrorReason reason) {
loadNextThumbnail();
}
}
private final class VideoListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onLoaded(String videoId) {
state = State.VIDEO_CUED;
}
#Override
public void onVideoEnded() {
state = State.VIDEO_ENDED;
imageWallView.showImage(videoCol, videoRow);
playerView.setVisibility(View.INVISIBLE);
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
if (errorReason == YouTubePlayer.ErrorReason.UNEXPECTED_SERVICE_DISCONNECTION) {
// player has encountered an unrecoverable error - stop the demo
flipDelayHandler.removeCallbacksAndMessages(null);
state = State.UNINITIALIZED;
thumbnailLoader.release();
thumbnailLoader = null;
player = null;
} else {
state = State.VIDEO_ENDED;
}
}
// ignored callbacks
#Override
public void onVideoStarted() { }
#Override
public void onAdStarted() { }
#Override
public void onLoading() { }
}
}
In this way, there are a list of videos in the playlist, each video will start automatically when the first is finished. I need to click each video in the wall for start it
You can add an onClickListener to the ImageViews in the ImageWallView.java class, something like this:
for (int col = 0; col < numberOfColumns; col++) {
for (int row = 0; row < numberOfRows; row++) {
int elementIdx = getElementIdx(col, row);
if (images[elementIdx] == null) {
ImageView thumbnail = new ImageView(context);
thumbnail.setLayoutParams(new LayoutParams(imageWidth, imageHeight));
images[elementIdx] = thumbnail;
unInitializedImages.add(elementIdx);
thumbnail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageWallView.this.context.startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(
ImageWallView.this.context, (String)v.getTag(), true, false));
}
});
}
addView(images[elementIdx]);
}
}
Then you will need to add the video id as the tag in YouTubeThumbnailView in VideoWallActivity.java
Hope that helps
You can use ImageView OnClickListener as suggested in previous answer: (onSizeChanged in ImageWallView.java)
for (int col = 0; col < numberOfColumns; col++) {
for (int row = 0; row < numberOfRows; row++) {
int elementIdx = getElementIdx(col, row);
if (images[elementIdx] == null) {
ImageView thumbnail = new ImageView(context);
thumbnail.setLayoutParams(new LayoutParams(imageWidth, imageHeight));
images[elementIdx] = thumbnail;
unInitializedImages.add(elementIdx);
thumbnail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageWallView.this.context.startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(
ImageWallView.this.context, (String)v.getTag(), true, false));
}
});
}
addView(images[elementIdx]);
}
}
Then you need to store video id to the calling view of ImageWallView . (set and get tag is also used to store objects between views).
To get the child view of ImageWallView, use imageWallView.getChildAt(index). index is the position of ImageView which is clicked on ImageWallView. to get this index, use getElementIdx(col,row). You need to make this method public in ImageWallView.java.
EDITED
To use the Video ID of current thumbnail, Store the VideoID in onFlipped event. This is because onThumbnailLoaded the VideoID of next thumbnail available which immediately get Flipped and available on IamgeWallView. As VideoID is not available in onFlipped event, use it from onThumbnailLoaded event
Here it is:
Declare below string in class
private String strThumbnailVideoId;
set VideoID in onThumbnailLoaded event (in VideoWallActivity.java) into strThumbnailVideoId. This video ID will be of next thumbnail which will be flipped.
#Override
public void onThumbnailLoaded(YouTubeThumbnailView thumbnail, String videoId) {
nextThumbnailLoaded = true;
strThumbnailVideoId = videoId;
if (activityResumed) {
if (state.equals(State.LOADING_THUMBNAILS)) {
flipNext();
} else if (state.equals(State.VIDEO_FLIPPED_OUT)) {
// load player with the video of the next thumbnail being flipped in
state = State.VIDEO_LOADING;
player.cueVideo(videoId);
}
}
}
Now set the strThumbnailVideoId in onFlipped as a ImageWallView tag.
#Override
public void onFlipped(FlippingView view) {
imageWallView.showImage(flippingCol, flippingRow);
flippingView.setVisibility(View.INVISIBLE);
imageWallView.getChildAt(imageWallView.getElementIdx(flippingCol, flippingRow)).setTag(strThumbnailVideoId);
......
......

Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to com.slidingmenu.lib.SlidingMenu

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.

Categories