In my MainActivity, I have "setContentView(R.layout.activity_main)". This activity_main layout contains a VideoView.
activity_main is not used in any fragment; when I switch to fragments I can't see the video (which is good), but if I tap the screen, then the video options (play,pause,etc.) pop up (not good). I'm assuming that main_activity is in the underneath every fragment because of "setContentView(R.layout.activity_main)"?
I need the video to be displayed in just a single fragment without affecting any other fragments. But, if I try to remove the VideoView from activity_main and instead identify it in a fragment layout (i.e. fragment_one), I get a NullPointerException. Again, I think this is because of "setContentView(R.layout.activity_main)". I'm thinking that views referenced in the java code must be identified (id="#+id/video_view") in activity_main?
The solution to this problem may be very simple, but I just can't seem to find any information that addresses it. I am certainly a novice, so please bear with me.
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
//used in VideoView
private VideoView myVideoView;
private int position = 0;
private ProgressDialog progressDialog;
private MediaController mediaControls;
String[] LabelMenu = {"Home","Flight Tracker"};
#Override
//Allows the use of icons in overflow-dropdown
protected boolean onPrepareOptionsPanel(View view, Menu menu) {
if (menu != null) {
if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
try {
Method m = menu.getClass().getDeclaredMethod(
"setOptionalIconsVisible", Boolean.TYPE);
m.setAccessible(true);
m.invoke(menu, true);
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "onMenuOpened...unable to set icons for overflow menu", e);
}
}
}
return super.onPrepareOptionsPanel(view, menu);
}
//***START OF GOTOURL REFERENCES***
public void goToUS (View view) {
goToUrl ( "http://10.100.1.200/imsg_weather_radar/weather_radar_united_states.html");
}
public void goToSW (View view) {
goToUrl( "http://10.100.1.200/imsg_weather_radar/weather_radar_southwest_us.html");
}
public void goToSE (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_southeast_us.html");
}
public void goToNW (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_northwest_us.html");
}
public void goToWP (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_west_pacific.html");
}
public void goToSP (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_south_pacific.html");
}
public void goToCC (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_carolina_coast.html");
}
public void goToWA (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_western_atlantic.html");
}
public void goToEU (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_eastern_us.html");
}
public void goToEGF (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_east_gulf_florida.html");
}
public void goToGM (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_gulf_of_mexico.html");
}
public void goToWGT (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_west_gulf_texas.html");
}
public void goToCI (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_caribbean_islands.html");
}
public void goToMX (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_mexico.html");
}
public void goToCA (View view) {
goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_central_america.html");
}
//***END OF GOTOURL REFERENCES***
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the main layout of activity
setContentView(R.layout.activity_main);
//set the media controller buttons
if (mediaControls == null) {
mediaControls = new MediaController(MainActivity.this);
}
//initialize the VideoView
myVideoView = (VideoView) findViewById(R.id.video_view);
// create a progress bar while the video file is loading
progressDialog = new ProgressDialog(MainActivity.this);
// set a title for the progress bar
progressDialog.setTitle("IAWS");
// set a message for the progress bar
progressDialog.setMessage("Loading...");
//set the progress bar not cancelable on users' touch
progressDialog.setCancelable(false);
// show the progress bar
progressDialog.show();
try {
//set the media controller in the VideoView
myVideoView.setMediaController(mediaControls);
//set the uri of the video to be played
myVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.iaws));
} catch (Exception e) {
if(e.getMessage()!=null) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
myVideoView.requestFocus();
//setOnPreparedListener in order to know when the video file is ready for playback
myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
// close the progress bar and play the video
progressDialog.dismiss();
//if we have a position on savedInstanceState, the video playback should start from here
myVideoView.seekTo(position);
if (position == 0) {
//remove comments if you want video to start automatically
//myVideoView.start();
} else {
//coming from a resumed activity, video playback will be paused
myVideoView.pause();
}
}
});
final ActionBar actionBar = getSupportActionBar();
// Specify that a dropdown list should be displayed in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Hide the title
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
//Adding an ImageView to Action Bar
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView imageView = new ImageView(actionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.drawable.imsg_blue_logo_rsz);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL);
layoutParams.rightMargin = 40;
layoutParams.bottomMargin=10;
imageView.setLayoutParams(layoutParams);
actionBar.setCustomView(imageView);
// Specify a SpinnerAdapter to populate the dropdown list.
ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(actionBar.getThemedContext(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.labelMenu));
//2nd Spinner dropdown
/**
Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
mySpinner.setAdapter(new MyCustomAdapter(MainActivity.this, R.layout.row, LabelMenu));
**/
actionBar.setListNavigationCallbacks(spinnerMenu,
// Provide a listener to be called when an item is selected.
new ActionBar.OnNavigationListener() {
public boolean onNavigationItemSelected(int position, long id) {
// Take action here, e.g. switching to the
// corresponding fragment.
FragmentTransaction tx = getFragmentManager().beginTransaction();
switch (position) {
case 0:
tx.replace(android.R.id.content, new FirstFragment());
break;
case 1:
tx.replace(android.R.id.content, new SecondFragment());
break;
case 2:
tx.replace(android.R.id.content, new ThirdFragment());
break;
case 3:
tx.replace(android.R.id.content, new FourthFragment());
break;
case 4:
tx.replace(android.R.id.content, new FifthFragment());
break;
default:
break;
}
tx.commit();
return true;
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Use onSaveInstanceState in order to store the video playback position for orientation change
savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());
myVideoView.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Use onRestoreInstanceState in order to play the video playback from the stored position
position = savedInstanceState.getInt("Position");
myVideoView.seekTo(position);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.about:
aboutMenuItem();
break;
case R.id.settings:
settingsMenuItem();
break;
case R.id.search:
searchMenuItem();
break;
}
return true;
}
//Configure "about" function
private void aboutMenuItem(){
new AlertDialog.Builder(this)
.setTitle("App & Copyright Info")
.setMessage("Version 1.0" + "\n" + "Property of I.M. Systems Group, Inc.")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();{
}
}
//Configure "settings" function
private void settingsMenuItem(){
new AlertDialog.Builder(this)
.setTitle("Settings")
.setMessage("Language: English" + "\n" + "Degrees Fahrenheit Selected" + "\n" +
"Show Airports" + "\n" + "Speed: KM/H" )
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();{
}
}
//Configure "search" function
private void searchMenuItem(){
new AlertDialog.Builder(this)
.setTitle("Search")
.setMessage("This is an about AlertDialog")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();{
}
}
}
I'd like this fragment to display the video exclusively. As it is now, the fragments will display their designated layouts just fine, but if you tap on the screen in any layout, the video options from main_activity's VideoView will pop up (that's bad). They're all pretty much coded the same way; they're only different in that they reference different layouts:
/**
* Created by ansaripours on 8/19/2015.
*/
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_one, container, false);
return (FrameLayout) inflater.inflate(R.layout.fragment_one, container, false);
}
}
Here's my main_activity.xml. It seems the ViewVideo has to be identified here, because it is referenced in setContentView, otherwise I get a NullPointerException:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#E1F4FF"
android:paddingTop="?android:attr/actionBarSize"
tools:context=".MainActivity">
<!-- implementing swipeable pages
<edu.dartmouth.cs.actiontabs.view.SlidingTabLayout
android:id="#+id/tab"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/tab"/>
-->
<!--
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:padding="100"/>-->
<!--
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" /> -->
<!--
<ImageView
android:src="#drawable/rsz_sampleweather"
android:id="#+id/cover_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
/>
-->
<VideoView
android:id="#+id/video_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"/>
</FrameLayout>
Finally, here's the layout that FirstFragment class references. It's literally the same as main_activity.xml (without the comments). However, like I said, if I remove the VideoView from main_activity.xml, I get a NullPointerException.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#E1F4FF"
android:paddingTop="?android:attr/actionBarSize"
tools:context=".MainActivity">
<VideoView
android:id="#+id/video_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"/>
</FrameLayout>
Feel free to ask any questions. Any insight would be much appreciated.
First of all, I recommend that you read the Android developer page on how to use Fragments: http://developer.android.com/guide/components/fragments.html.
You should be able to define a container for a fragment in your activity_main.xml and create a separate Fragment that holds your VideoView, which can be replaced by another Fragment using a FragmentTransaction.
Related
I have my main activity which contains 2 fragments:
MainActivity
public class MainActivity extends AppCompatActivity implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
FragmentOne fragmentOne = new FragmentOne ();
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragmentOne ).commit();
}
}
This activity initially display fragment one.
Fragment one has a button which listens and when clicked it will replace itself with fragment two. When the button is clicked the interface in fragment one gets
//Main acitivty has this method which is a a method the interface in fragment one requires
#Override
public void goToFragmentTwo() {
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// Create fragment and give it an argument specifying the article it should show
FragmentTwo fragmentTwo = new FragmentTwo ();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, fragmentTwo );
transaction.addToBackStack(FragmentTwo.BACKSTACK_TAG);
// Commit the transaction
transaction.commit();
}
If the android back button or the back button in the toolbar gets called the fragments need to have a confirm dialog which asks are you sure you want to leave. If Ok then I have a second activity called the HomeActivity (this activity is the parent activity of MainActivity) which it needs to go to, or if cancel it needs to just close the dialog and stay in the current fragment.
So in the MainActivity I have overrode the onBackPressed method which displays a :
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to leave? ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.show();
}
I am experiencing two problems with this code:
1) Pressing the back button in the toolbar doesn't display a dialog
2) The dialog's OK and Cancel features are not working correctly.
Essentially what I am trying to accomplish is I have a HomeActivity which has a button to navigate to the MainActivity. When the MainActivity gets called I will start a workflow where each fragment is a section of that workflow. If the back button is pressed this workflow needs to be discarded and the user should be returned back to the HomeActivty.
i am assuming you are using ActionBar.
Try adding this in your activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to leave? ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.show();
}
1) You should make your toolbar back button call onBackPressed() from your activity, so they both share the same functionality.
See onSupportNavegationUp() in the main activity.
2) Have your Main Activity control what happens with the fragment, but let the fragments handle any back press if they must.
I hope this is of use to you.
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.johnurrutia.so_43172788">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.johnurrutia.so_43172788.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
</android.support.v7.widget.Toolbar>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="#id/toolBar"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_editor_absoluteY="8dp">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
fragment_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btnGoFrag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go To Fragment TWO" />
</LinearLayout>
fragment_two.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/goToFragmentOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Go To Fragment One" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity
implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener {
public static final int FRAGMENT_ONE = 0;
public static final int FRAGMENT_TWO = 1;
private Toolbar toolbar;
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
private ArrayList<Fragment> fragments = new ArrayList<>();
private int currentFragment = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
fragments.add(FRAGMENT_ONE, fragmentOne);
fragments.add(FRAGMENT_TWO, fragmentTwo);
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragmentOne,"FRAGMENT_ONE")
.add(R.id.fragment_container, fragmentTwo, "FRAGMENT_TWO")
.hide(fragmentTwo)
.show(fragmentOne)
.commit();
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onBackPressed() {
boolean fragmentProcessedTheEvent = ( (BackButtonListener) fragments.get(currentFragment)).onBackPressed();
if(!fragmentProcessedTheEvent) {
//The event is for Main Activity to exit
showActivityExitDialog();
}
}
public void showActivityExitDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to leave? ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();
}
private void switchToFragment(int pos) {
if (currentFragment != pos) {
getSupportFragmentManager().beginTransaction()
.hide(fragments.get(currentFragment))
.show(fragments.get(pos))
.commit();
currentFragment = pos;
}
}
public void goToFragmentTwo(){
switchToFragment(FRAGMENT_TWO);
}
public void goToFragmentOne(){
switchToFragment(FRAGMENT_ONE);
}
}
FragmentOne.java
public class FragmentOne extends Fragment implements BackButtonListener{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_one, container, false);
Button goToFragmentTwoBtn = (Button) v.findViewById(R.id.btnGoFrag2);
goToFragmentTwoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
( (OnFragmentOneInteractionListener) getActivity() ).goToFragmentTwo();
}
});
return v;
}
public interface OnFragmentOneInteractionListener{
public void goToFragmentTwo();
}
#Override
public boolean onBackPressed() {
/*
* if(fragment_has_any_use_for_back_press){
* process_it_here();
* return EVENT_PROCESSED;
* }
*
* */
return EVENT_IGNORED;
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment implements BackButtonListener{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_two, container, false);
Button goToFragmentTwoBtn = (Button) v.findViewById(R.id.goToFragmentOne);
goToFragmentTwoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
( (FragmentTwo.OnFragmentTwoInteractionListener) getActivity() ).goToFragmentOne();
}
});
return v;
}
#Override
public boolean onBackPressed() {
/*
* if(fragment_has_any_use_for_back_press){
* process_it_here();
* return EVENT_PROCESSED;
* }
*
* */
return EVENT_IGNORED;
}
public interface OnFragmentTwoInteractionListener{
public void goToFragmentOne();
}
}
BackButtonListener.java
public interface BackButtonListener {
public static final boolean EVENT_PROCESSED = true;
public static final boolean EVENT_IGNORED = false;
public boolean onBackPressed();
}
I have a ViewPager in my MainActivity. Every page in it is a Fragment. So, everytime I swipe right or left, a new instance of the fragment is created and the fragment view is updated accordingly.
I also have two buttons: LEFT and RIGHT for navigation. These buttons are inside the Fragment, not in the Activity. A user can either swipe or alternatively press the relevant button to navigate between the pages.
Here's the problem: Since I'm changing the views through my MainActivity, how do I detect the onClick events of those buttons in the Activity in order to update the fragment?
Here's the PagerAdapter class (Removed all the irrelevant code from everywhere):
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// logic part for the views.
return PlaceholderFragment.newInstance(sectionNumber, questionStatus, questionOrder, showNext, showPrevious);
}
And here's the PlaceHolderFragment class:
public class PlaceholderFragment extends Fragment{
//some global variables
public static PlaceholderFragment newInstance(int sectionNumber, int questionStatus, String questionOrder, boolean showNext, boolean showPrevious) {
PlaceholderFragment fragment = new PlaceholderFragment();
//setting up the arguments
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.explanation_fragment, container, false);
//code for filling up all the views
RightButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//can I do something here?
}
});
return rootView;
}
}
MORE INFO:
I have to keep the navigation buttons in the fragment itself and not in the activity.
In your fragment write one interface like:
public class PlaceholderFragment extends Fragment{
private OnButtonClickListener mOnButtonClickListener;
interface OnButtonClickListener{
void onButtonClicked(View view);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mOnButtonClickListener = (OnButtonClickListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(((Activity) context).getLocalClassName()
+ " must implement OnButtonClickListener");
}
}
yourButtons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnButtonClickListener.onButtonClicked(v);
}
});
}
And in your mainactivity:
class MainActivity extends AppCompatActivity implements OnButtonClickListener{
#Override
void onButtonClicked(View view){
int currPos=yourPager.getCurrentItem();
switch(view.getId()){
case R.id.leftNavigation:
//handle currPos is zero
yourPager.setCurrentItem(currPos-1);
break;
case R.id.rightNavigation:
//handle currPos is reached last item
yourPager.setCurrentItem(currPos+1);
break;
}
}
}
For Kotlin and ViewPager2
previous page:
val currPos: Int = xyzViewPager.currentItem
if (currPos != 0) {
xyzViewPager.currentItem = currPos - 1
}
next page:
val currPos: Int = xyzViewPager.currentItem
if ((currPos + 1) != xyzViewPager.adapter?.count) {
xyzViewPager.currentItem = currPos + 1
}
Use kotlin extension functions:
fun ViewPager2.nextPage(smoothScroll: Boolean = true): Boolean {
if ((currentItem + 1) < adapter?.itemCount ?: 0) {
setCurrentItem(currentItem + 1, smoothScroll)
return true
}
//can't move to next page, maybe current page is last or adapter not set.
return false
}
fun ViewPager2.previousPage(smoothScroll: Boolean = true): Boolean {
if ((currentItem - 1) >= 0) {
setCurrentItem(currentItem - 1, smoothScroll)
return true
}
//can't move to previous page, maybe current page is first or adapter not set.
return false
}
Make a public method in your activity
public void swipeRight(int x){
if(x < totalNumberOfFragment){
viewPager.setCurrentItem(x + 1);
}
}
public void swipeLeft(int x){
if(x > 0){
viewPager.setCurrentItem(x - 1);
}
}
You can call these method from your fragment button's click action
RightButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Yes
((YourActivityClassName)getActivity()).swipeRight(position);
}
});
And do same for LeftButton
YourActivityClassName - Activity which is holding this viewPager fragment.
position - position of your current fragment.
You can add button in your activities xml as follows
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
</LinearLayout>
<ImageView
android:id="#+id/leftNavigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:padding="10dp"
android:src="#drawable/ic_chevron_left_black_24dp"
android:visibility="gone" />
<ImageView
android:id="#+id/rightNavigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="0"
android:gravity="center"
android:padding="10dp"
android:src="#drawable/ic_chevron_right_black_24dp" />
</FrameLayout>
You can create special method in your parent Activity like following:
public class PagerActiviy extends Activity {
...
public void onFragmentNavigationButtonClick(View button) {
// Do your stuff here
}
...
}
Then in your fragments you can get your parent Activity with getActivity() method, cast it to the actual type and call the method:
public class PlaceholderFragment extends Fragment{
...
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.explanation_fragment, container, false);
//code for filling up all the views
RightButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((PagerActvity) getActivity()).onFragmentNavigationButtonClick(v);
}
});
return rootView;
}
}
As a side note I should add that from your example it's not clear why do you need to keep your navigation buttons in the fragments and can't move them to the Activity and manage them there.
You can send a broadcast upon button click inside the fragment like below:
Intent intent = new Intent();
intent.setAction(NUMBER_OF_RECEIVER_NEXT);
getActivity().sendBroadcast(intent);
Then in your main activity you catch the Intent and you set the current position of the pager to the desired number
private class broadcastReceived extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String actionGet = intent.getAction();
if(actionGet.equals(NUMBER_OF_RECEIVER_NEXT)){
mPager.setCurrentItem(1);
Log.e("IntentNextPage","Received");
}
}
}
Do not forget to set a
private static final String NUMBER_OF_RECEIVER_NEXT = "nextPage";
in both main activity and fragment and of course to register,unregister receiver to onResume and onPause methods.
Also add an intent filter to the receiver in onCreate methd with the action specified as NUMBER_OF_RECEIVER_NEXT
I'm trying to show a nested fragment inside my fragment on button click, so on button .setOnClickListener (which works fine with Log.d) of my main fragment i've placed:
Fragment noteFragment = new FrontPageNote();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.frontNote, noteFragment).commit();
as found on developer guide, where FrontPageNote is my nested fragment (which obviously extends Fragment) and R.id.frontNote is the id of the xml layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="48dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:layout_weight="1"
android:id="#+id/frontNote"
android:background="#color/Background">
<LinearLayout
android:id="#+id/linearLayoutFront"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:paddingTop="15dp">
<EditText
android:id="#+id/titleEditFront"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/titleEdit"
android:textColor="#color/TextColor.White"/>
<EditText
android:id="#+id/noteEditFront"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/noteEdit"
android:paddingTop="20dp"
android:textColor="#color/TextColor.White"
android:inputType="textMultiLine" />
</LinearLayout>
</RelativeLayout>
the nested fragment FrontPageNote also is linked to this xml using getActivity().setContentView(R.layout.front_note); under onCreate() method.
Q. what am I doing wrong? thanks
EDIT: added FrontPageNote.class:
public class FrontPageNote extends Fragment {
// Declare Variables
public static long rowID;
private EditText title_edit;
private EditText note_edit;
private static final String TITLE = "title";
private static final String NOTE = "note";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setContentView(R.layout.front_note);
// Locate the EditText in add_note.xml
title_edit = (EditText) getActivity().findViewById(R.id.titleEditFront);
note_edit = (EditText) getActivity().findViewById(R.id.noteEditFront);
// Retrieve the Row ID from ViewNote.java
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
rowID = extras.getLong("row_id");
title_edit.setText(extras.getString(TITLE));
note_edit.setText(extras.getString(NOTE));
}
}
// Create an ActionBar menu
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_all_geofences, menu);
menu.add("Save changes")
.setOnMenuItemClickListener(this.SaveButtonClickListener)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
super.onCreateOptionsMenu(menu, inflater);
}
// Capture save menu item click
OnMenuItemClickListener SaveButtonClickListener = new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// Passes the data into saveNote() function
if (title_edit.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveNoteAsyncTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveNote();
return null;
}
#Override
protected void onPostExecute(Object result) {
// Close this activity
//getActivity().finish();
}
};
// Execute the saveNoteAsyncTask AsyncTask above
saveNoteAsyncTask.execute((Object[]) null);
}
else {
// Display a simple alert dialog that forces user to put in a title
AlertDialog.Builder alert = new AlertDialog.Builder(
getActivity());
alert.setTitle("Title is required");
alert.setMessage("Put in a title for this note");
alert.setPositiveButton("Okay", null);
alert.show();
}
return false;
}
};
// saveNote() function
private void saveNote() {
DatabaseConnector dbConnector = new DatabaseConnector(getActivity());
if (getActivity().getIntent().getExtras() == null) {
// Passes the data to InsertNote in DatabaseConnector.java
dbConnector.InsertNote(title_edit.getText().toString(), note_edit
.getText().toString());
} else {
// Passes the Row ID and data to UpdateNote in DatabaseConnector.java
dbConnector.UpdateNote(rowID, title_edit.getText().toString(),
note_edit.getText().toString());
}
}
}
In Android if I start new Activity B from within activity A, Android will automatically save all the state of Activity A. So when I click back button on the device in Activity B, A will be restored to the state when I had started Activity B (for example: Spinners, ListView and Toggle Buttons all are in their previous positions).
BUT when I click the back button in action bar activity A starts fresh with no stored state.
Is there any way to make this back button similar to the device's back or I have to use SharedPreferences and store every thing myself?
(api 8 and above for my app)
In one of the fragments in my app I have a ListView which is one of the fragments that needs to be in the same state when coming back from the next page. I have added the code below.
If any other part is needed please tell me and I will add the code.
The main activity code:
private ProgressDialog progress;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(Farsi.Convert(getString(R.string.app_name_farsi)));
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab. We can also use ActionBar.Tab#select() to do this if we have a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter. Also specify this Activity object, which implements the TabListener interface, as the callback (listener) for when this tab is selected.
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will automatically handle clicks on the Home/Up button, so long as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent=new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
Here is the code to my List Fragment:
public class SearchResultListFragment extends Fragment{
Pagination pagination;
boolean loadingMore = false;
ListView list;
TextView text1;
TextView text2;
TextView text3;
TextView text4;
TextView text5;
Button Btngetdata;
private static String url = "https://www.....com/api/property/search";
private static int currentFirstVisibleItem;
public SearchResultArrayListAdaptor adapter ;
LinearLayout linlaHeaderProgress;
JSONArray jsonArray = null;
JSONParse fetchclass = null;
public SearchResultListFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linlaHeaderProgress = (LinearLayout) getActivity().findViewById(R.id.linlaHeaderProgress);
ArrayAdapter<PropertyObject> aa =(ArrayAdapter<PropertyObject>) list.getAdapter();
if (aa!= null){
aa.clear();
aa.notifyDataSetChanged();
}
list.setOnItemClickListener((OnItemClickListener) getActivity());
adapter = new SearchResultArrayListAdaptor(getActivity(), R.layout.list_view_items, new ArrayList<PropertyObject>());
list.setAdapter(adapter);
pagination = new Pagination(0,15);
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search_result_list, container, false);
list=(ListView)rootView.findViewById(R.id.listViewSearchResult);
list.setOnScrollListener(
new OnScrollListener(){
private int currentVisibleItemCount;
private int currentTotalItemCount;
private int currentScrollState;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
if(fetchclass!=null) {
pagination = new Pagination(this.currentTotalItemCount,15);
if(!(fetchclass.getStatus()== AsyncTask.Status.RUNNING)) {
fetchclass= new JSONParse(getActivity());
fetchclass.execute(url);
}
}
else {
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
});
return rootView;
}
//*********************************** inner class
public class JSONParse extends AsyncTask<String, String, JSONObject> {
Context mContext;
int checkBoxRooms;
public JSONParse(Context context){
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject json = null;
PropertyFilter searchFilter = SearchFilterManager.initializePropertyFilter(new PropertyFilter(), getArguments());
getActivity().setProgressBarIndeterminateVisibility(true);
JSONParserForSearch jParser = new JSONParserForSearch();
json = jParser.getJSONFromUrl(url, searchFilter, pagination);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// SHOW THE SPINNER WHILE LOADING FEEDS
getActivity().setProgressBarIndeterminateVisibility(false);
PropertyObject propertyObject;
try {
jsonArray = json.getJSONArray("PropertyListings");
if (jsonArray == null || jsonArray.length()<1){
// list.setEmptyView(getActivity().findViewById(R.id.txtNoResult));
}
else {
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
adapter.add(propertyObject);
adapter.notifyDataSetChanged();
}
}
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
<ListView
android:id="#+id/listViewSearchResult"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
>
</ListView>
<LinearLayout
android:id="#+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone"
>
My Adapter is ArrayAdapter.
I have implemented isEmpty and getCount too.
My Activity For List:
public class SearchResultListActivity extends ActionBarActivity implements OnItemClickListener{
static PropertyObject selectedPropertyObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle=new Bundle();
bundle.putInt("intentionOfOwner", intent.getIntExtra("intentionOfOwner",0));
SearchResultListFragment fragobj=new SearchResultListFragment();
fragobj.setArguments(bundle);
///back button
setContentView(R.layout.activity_search_result_list);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, fragobj).commit();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View textView, int rowNumber, long arg3) {
Intent intent = new Intent(this, PropertyDetailActivity.class);
PropertyObject po = (PropertyObject) arg0.getAdapter().getItem((int)arg3);
intent.putExtra("listingID",po.getID());
startActivity(intent);
}
EDIT:
All right. I changed my API level from 8 to 11 to.
Also I added getActionBar().setDisplayHomeAsUpEnabled(true); to onCreate() of activity.
And changes the onOptionsItemSelected as follows.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent=new Intent(PropertyDetailActivity.this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.up:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.homeAsUp:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
BUT none of the switch cases gets the chance to run when I click the back button in the action bar!
I'm trying to implement the Click event for fragments that display images or buttons.
I am able to implement the flip view to get another fragment but I am unable get the click event working on such fragments.
I have tried with android:onClick, even setting clickable to true. I even tried with onClickListener and onTouch but it's not firing for me.
This is the code I have tried.
public class MainActivity extends Activity {
private FlipViewGroup contentView;
public int currentimageindex=0;
private GestureDetector mDetector;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hde staitbar otef Andoroid
// could also be usdne lar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setTitle(R.string.activity_title);
contentView = new FlipViewGroup(this);
contentView.addFlipView(View.inflate(this, R.layout.second_page, null));
contentView.addFlipView(View.inflate(this, R.layout.first_page, null));
setContentView(contentView);
// setContentView(R.layout.second_page);
contentView.startFlipping(); //make the first_page view flipping
ImageView imgFavorite = (ImageView) findViewById(R.id.imageView1);
imgFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
}
#Override
protected void onResume() {
super.onResume();
contentView.onResume();
}
#Override
protected void onPause() {
super.onPause();
contentView.onPause();
}
public void onclick(View v){
ImageView imgFavorite = (ImageView) findViewById(R.id.imageView1);
imgFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}
});
}
}
This is my xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#android:color/white">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView5"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:src="#drawable/android"
android:clickable="true"
android:onClick="onclick"/>
</RelativeLayout>
Is there some reason a fragment within a flip view doesn't respond to click or touch events, or is there something I'm doing wrong in my code?
As far as i understand, FlipViewGroup is your custom view group implementation.
If that is the case you need onInterceptTouchEvent() see the sample code here.
http://developer.android.com/training/gestures/viewgroup.html