Click event for flipview or swipe view - android

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

Related

How to remove main layout from being in every fragment

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.

Android how to action bar action(customize layout) for different tabs?

I am using Actionbar support library. I customized the title and added one button in layout.
Now, I have 2 action tabs with extension of fragment. I want use same button for different functions in different tabs.
I am using Actionbar activity. Below is my code.
Custom action bar 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="wrap_content"
android:background="#00FFFFFF" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="1"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/app_green" />
<CheckBox
android:id="#+id/selectAll"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_gravity="top|right"
android:button="#drawable/checkbox"
android:focusable="false"
android:focusableInTouchMode="false" />
</RelativeLayout>
My first fragment
public class TestPhotos extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
selectAll();
}
private void selectAll() {
CheckBox b = (CheckBox) getActivity().findViewById(R.id.selectAll);
if (AutoBackupSettings.getInstance().isPhotoBackup()) {
b.setVisibility(View.INVISIBLE);
transferLayout.setVisibility(View.VISIBLE);
} else {
b.setVisibility(View.VISIBLE);
transferLayout.setVisibility(View.GONE);
}
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (stickyAdapter != null) {
if (stickyAdapter.getSelectedCount() == stickyAdapter.list
.size()) {
stickyAdapter.deselectAll();
} else {
stickyAdapter.selectAll();
((PhotosActivity) getActivity())
.setActionBarTitle(getResources().getString(
R.string.all));
}
}
}
});
}
}
My second fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
selectAll();
}
private void selectAll() {
CheckBox b = (CheckBox) getActivity().findViewById(R.id.selectAll);
if (AutoBackupSettings.getInstance().isPhotoBackup()) {
b.setVisibility(View.INVISIBLE);
} else {
b.setVisibility(View.VISIBLE);
}
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (listAdapter != null) {
if (listAdapter.getSelectedCount() == listAdapter.list
.size()) {
listAdapter.deselectAll();
} else {
listAdapter.selectAll();
((PhotosActivity) getActivity())
.setActionBarTitle(getResources().getString(
R.string.all));
}
}
}
});
}
It's working fine in first fragment but I swipe to the second fragment and click on checkbox, it is working for first fragment but not for second one.

Android Class Cast Exception Error, when I am casting correctly?

I am new to android development and I cannot understand this error, I am making a simple stop watch app, it has a Chronometer and 3 buttons (Start, stop, reset) I define all of these in the main java file correctly with their correct tags.
Its strange because I tested the app before and my app was working fine, but then I re-positioned the buttons in the GUI, and now it is saying that I am not casting the chronometer correctly.
06-06 19:11:07.488: E/AndroidRuntime(21511): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shitstopwatch/com.example.shitstopwatch.ShittyClockActivity}: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.Chronometer
here is the main java file:
public class ShittyClockActivity extends ActionBarActivity {
Button Start;
Button Stop;
Button Reset;
Chronometer mainChronometer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shitty_clock);
mainChronometer = (Chronometer) this.findViewById(R.id.mainChronometer);
Start = (Button) this.findViewById(R.id.startButton);
Stop = (Button) this.findViewById(R.id.stopButton);
Reset = (Button) this.findViewById(R.id.resetButton);
addButtonListeners();
}
private void addButtonListeners()
{
Start.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
int stoppedMilliseconds = 0;
mainChronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
mainChronometer.start();
}
});
Stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mainChronometer.stop();
}
});
Reset.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mainChronometer.setBase(SystemClock.elapsedRealtime());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shitty_clock, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}public class ShittyClockActivity extends ActionBarActivity {
Button Start;
Button Stop;
Button Reset;
Chronometer mainChronometer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shitty_clock);
mainChronometer = (Chronometer) this.findViewById(R.id.mainChronometer);
Start = (Button) this.findViewById(R.id.startButton);
Stop = (Button) this.findViewById(R.id.stopButton);
Reset = (Button) this.findViewById(R.id.resetButton);
addButtonListeners();
}
private void addButtonListeners()
{
Start.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
int stoppedMilliseconds = 0;
mainChronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
mainChronometer.start();
}
});
Stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mainChronometer.stop();
}
});
Reset.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mainChronometer.setBase(SystemClock.elapsedRealtime());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shitty_clock, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
and here is the activity XML with the ID tags:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.shitstopwatch.ShittyClockActivity$PlaceholderFragment" >
<Chronometer
android:id="#+id/mainChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="#string/chronometer"
android:textSize="#dimen/BigText" />
<Button
android:id="#+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/mainChronometer"
android:layout_below="#+id/mainChronometer"
android:layout_marginTop="63dp"
android:text="#string/startButton" />
<Button
android:id="#+id/resetButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/startButton"
android:layout_below="#+id/startButton"
android:layout_marginTop="16dp"
android:text="#string/resetButton" />
<Button
android:id="#+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/resetButton"
android:layout_below="#+id/resetButton"
android:layout_marginTop="20dp"
android:text="#string/stopButton" />
</RelativeLayout>
Clean your project (e.g., Project > Clean in Eclipse).
Sometimes, the R constants get out of sync with the resource entries in the APK file, causing this error.

Android app is closing on press of back button

I have a menu and when clicked on a menu, it goes inside another menu.
for example, mainmenu-->click on airport guide --> menu2
but when i am in menu2 and press on the back button, the app is closing instead of going back to mainmenu . i am not able to figure out the problem here. i am new to android development
package com.shashank.sharjahinternationalairport;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class MainActivity extends Activity {
ImageButton flightInfoButton;
ImageButton airportGuideButton;
ImageButton visitorInfoButton;
ImageButton saaDcaButton;
ImageButton cargoButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flightInfoButton = (ImageButton) findViewById(R.id.flightInfo);
airportGuideButton = (ImageButton) findViewById(R.id.airportGuide);
visitorInfoButton = (ImageButton) findViewById(R.id.visitorInfo);
saaDcaButton = (ImageButton) findViewById(R.id.saaDca);
cargoButton = (ImageButton) findViewById(R.id.cargo);
airportGuideButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.airport_guide);
}
});
visitorInfoButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.visitor_info);
}
});
saaDcaButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View V){
setContentView(R.layout.saa_dca);
}
});
}
#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;
}
You are using setContentView, so you are just changing the view layout. When you press the backbutton, the Android calls onBackPressed, which the default implementation is to call finnish() method, that closes the activity.
You can override the onBackPressed method to set the other view.
#Override
public void onBackPressed()
{
//setContentView the previous view
}
Hope it helps!
you can always override the onBackPressed method of Activity, you'll have something like this
public class MainActivity extends Activity {
ImageButton flightInfoButton;
ImageButton airportGuideButton;
ImageButton visitorInfoButton;
ImageButton saaDcaButton;
ImageButton cargoButton;
private enum VIEWS {
VIEW_1, VIEW_2, VIEW_3
};
private VIEWS mSelectedView = VIEWS.VIEW_1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flightInfoButton = (ImageButton) findViewById(R.id.flightInfo);
airportGuideButton = (ImageButton) findViewById(R.id.airportGuide);
visitorInfoButton = (ImageButton) findViewById(R.id.visitorInfo);
saaDcaButton = (ImageButton) findViewById(R.id.saaDca);
cargoButton = (ImageButton) findViewById(R.id.cargo);
airportGuideButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView1();
}
});
visitorInfoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView2();
}
});
saaDcaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
showView3();
}
});
}
private void showView1() {
setContentView(R.layout.airport_guide);
mSelectedView = VIEWS.VIEW_1;
}
private void showView2() {
setContentView(R.layout.visitor_info);
mSelectedView = VIEWS.VIEW_2;
}
private void showView3() {
setContentView(R.layout.saa_dca);
mSelectedView = VIEWS.VIEW_3;
}
#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 void onBackPressed() {
switch (mSelectedView) {
case VIEW_1:
super.onBackPressed();
break;
case VIEW_2:
showView1();
break;
case VIEW_3:
showView2();
break;
}
}
}
All you is doing that you are changing the Content View of the class MainActivity you need to create sperate classes for your difreent layouts and you can call it by INTENT
This is happennig because you are using only one activity, and on click just changing the content view. Even though this appears like a multi page activity, it is only one screen. Hence onBackPressed() it closes. Yo will have to create different activiies for each of your menu options and start them using Intents on Button Click.
Intent i = new Intent(this, SecondActivity.class);
startActivity(i);
You are using only one activity, if it is many activity mean you can track back to previously loaded activity.
else you must needed only one activity mean please store the layouts in some array, then in the onBackPressed() you can it get LIFO manner
#Override
public void onBackPressed() {
}

android OnAnimationEnd, not possible to add image to layout in OnAnimationEnd

`Hi everybody, i have a problem with Android OnAnimationEnd. i have two layouts A and B, A is the parent parent layout and contains B in the middle and an ImageView (imv) at the bottom. Now i need to translate imv from its original position into layout B which is at the middle of layout A such that at the end of the animation imv will belong to layout B and not layout A. to achieve this, in OnAnimationEnd, I removed imv from its parent layout and attempted to then add it to layout B. However at the end the animation imv just vanish as soon as it enters layout B. System.out shows that OnAnimationEnd is called and layout childCount also shows that imv is added to layout B, but imv is never vissible in layout B. below is the code, by the way am not an experienced android developer. Thanks in advance.
public class MainActivity extends Activity implements AnimatorListener {
ImageView imv;
RelativeLayout parentL;
RelativeLayout middleL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imv = (ImageView) findViewById(R.id.imageView1);
imv.setOnClickListener(new MyClick(this));
parentL = (RelativeLayout) findViewById(R.id.rl);
middleL = (RelativeLayout) findViewById(R.id.rll);
}
private class MyClick implements OnClickListener {
MainActivity ma;
public MyClick(MainActivity ma) {
this.ma = ma;
}
#Override
public void onClick(View v) {
ImageView imv = (ImageView) v;
float x = middleL.getX();
float y = middleL.getY();
imv.animate().setListener(ma);
imv.animate().x(x).y(y);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onAnimationCancel(Animator arg0) {
}
#Override
public void onAnimationEnd(Animator anim) {
System.out.println("onAnimationEnd");
ViewGroup vg = (ViewGroup)imv.getParent();
vg.removeView(imv);
middleL.addView(imv);
System.out.println("layout child count = "+middleL.getChildCount());
}
#Override
public void onAnimationRepeat(Animator arg0) {
}
#Override
public void onAnimationStart(Animator arg0) {
System.out.println("onAnimationStart");
}
}
Try to call invalidate(), it will tell the view it needs to redraw itself
when you define your animation, try using anim.setFillAfter(true);

Categories

Resources