Can I open a seperate XML layout with a OnLongClick - java

I am currently experimenting with layouts and opening new pages, I would like to open one page with a OnLongClickListener but a toast with a OnClickListener using the same text view box.
This is what I've designed so far. It won't work as the long click needs to output a boolean. Any Ideas?
XML main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.how_to_use.MainActivity"
android:id="#+id/main_view">
<TextView
android:id="#+id/long_press_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Long Press To Open \n'Drag n Drop'"/>
</LinearLayout>
XML 2nd page
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:id="#+id/swirl_img"
android:src="#drawable/Swirl"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.Java
public class MainActivity extends AppCompatActivity {
private LinearLayout mainView;
private TextView txtView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.long_press_textView);
addListenerLongPressBtn();
addListenerOnClickBtn();
}
public void addListenerOnClickBtn() {
txtView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Press Secret Button for Longer", Toast.LENGTH_SHORT).show();
}
});
}
public void addListenerLongPressBtn() {
txtView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(this, DragDropActivity.class);
startActivity(intent);
return true;
}
});
}
}

I found a solution to my own problem.
public void addListenerLongPressBtn() {
txtView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(view.getContext(), DragDropActivity.class);
startActivity(intent);
return true;
}
});
}

Related

Android pass onClick to child

Hello my goal is to make my custom view (ViewCircleOfInterest.java) receiving onClick. Now every time I click onClickListener on ViewCircleOfInterest.java is not called.
My interesting part of layout looks like that:
my_layout.xml
<FrameLayout
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/rl"
android:layout_alignParentTop="true"
android:background="#bbb">
<abc.x.y.ViewCircleOfInterest
android:id="#+id/view_circle_of_interest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
I have FrameLayout on my layout and I added view (SurfaceView - CameraPreview.java) to it like that
MyActivity.java
rootView = findViewById(android.R.id.content).getRootView();
viewCircleOfInterest = rootView.findViewById(R.id.view_circle_of_interest);
viewCircleOfInterest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewWayMeasurementActivity.this, "circle a", Toast.LENGTH_SHORT).show();
}
});
(...)
((FrameLayout) rootView.findViewById(R.id.camera_view)).addView(cameraPreview);
(...)
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
On CameraPreview.java in my init() method I do like that:
(...)
viewCircleOfInterest = ((NewWayMeasurementActivity)activity).viewCircleOfInterest;
viewCircleOfInterest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "circle aa", Toast.LENGTH_SHORT).show();
}
});
I also set onClickListener on my ViewCircleOfInterest.java
public ViewCircleOfInterest(SurfaceView surfaceView) {
super(surfaceView.getContext());
this.surfaceView = surfaceView;
setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(surfaceView.getContext(), "circle aaa", Toast.LENGTH_SHORT).show();
}
But unfortunately non of this method works, I still cannot receive onclicks from my custom view. How to solve that? I hope my question and code is understandable.
Make these changes in your code and check if it works.
my_layout.xml
<FrameLayout
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/rl"
android:layout_alignParentTop="true"
android:background="#bbb">
<abc.x.y.ViewCircleOfInterest
android:id="#+id/view_circle_of_interest"
android:layout_width="wrap_content"
android:clickable="true"
android:layout_height="wrap_content"/>
</FrameLayout>
MyActivity.java
((FrameLayout)rootView.findViewById(R.id.camera_view)).addView(cameraPreview,0);
Here we are adding cameraPreview at 0 index so your custom view is on top now and that should receive clicks.

How to change images using next and previous buttons?

sorry for annoying you but i am in my first step in android programming and need your support
the question is,
i want to change between photos using next and previous Button
i have 3 photos in an array
and 2 button (next and previous )
put when i started my app. i should press next button twice to change the photo
also in previous i should press it twice to change back
hope someone help me to improve the code down
public class SabahList extends AppCompatActivity {
ImageView img;
int[] mario = new int[]{R.drawable.image_a,R.drawable.image_b,R.drawable.image_c};
int n =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah_list);
img= (ImageView)findViewById(R.id.imageView2);
}
public void btu_next(View view) {
img.setImageResource(mario[n]);
if(n<2)
n++;
}
public void btu_prev(View view) {
img.setImageResource(mario[n]);
if(n>0)
n--;
}
}
Here is your logic problem. Your button's function command them set resource first, then increase/decease value, therefore when you click the second time, it will be set as previous increasingly/decreasingly.
public void btu_next(View view) {
if(n < 2)
n++;
img.setImageResource(mario[n]);
}
This answer may helpful to you if you are using normal array added images from drawable
//Your xml like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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.devobal.quitchet.SabahList"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/previous"
android:text="previous"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:text="next"/>
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
//And your Activity like this
public class SabahList extends AppCompatActivity {
ImageView imageView2;
Button previous,next;
int i=0;
private int[] textureArrayWin = {R.drawable.star1,R.drawable.star2, R.drawable.star3,};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah_list);
imageView2 = (ImageView)findViewById(R.id.imageView2);
previous = (Button)findViewById(R.id.previous);
next = (Button)findViewById(R.id.next);
if(i==0){
previous.setVisibility(View.GONE);
}
if (i==2){
next.setVisibility(View.GONE);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageView2.setImageResource(textureArrayWin[i]);
i--;
if(i==0){
previous.setVisibility(View.GONE);} else{ previous.setVisibility(View.VISIBLE);}
if (i==2){
next.setVisibility(View.GONE);
} else{next.setVisibility(View.VISIBLE)}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if you are loading from bitmap
imageView2.setImageResource(textureArrayWin[i]);
i++;
if(i==0){
previous.setVisibility(View.GONE); } else {previous.setVisibility(View.VISIBLE); }
if (i==2){
next.setVisibility(View.GONE);
} else{next.setVisibility(View.VISIBLE)}
}
});
}
}

EditText being overlapped by keyboard with custom animation

My EditText are being covered by my keyboard when trying to input into it.
Here's a screenshot without the Keyboard
Here's a screenshot with the Keyboard
When it comes to the code, I tried everything I could find here I think it comes from the fact that I use a custom animations. Here's the XML part of the code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:paddingTop="25dp">
<!--French Flag !-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="65dp"
android:orientation="vertical"
android:id="#+id/linearLayout">
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagBlue">
</View>
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagWhite">
</View>
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagRed">
</View>
</LinearLayout>
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:id="#+id/logo"
android:src="#drawable/logo_text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<com.facebook.login.widget.LoginButton
android:id="#+id/button_facebook_sign_in"
android:layout_width="200dp"
android:layout_height="45dp"
android:layout_marginTop="100dp"
android:layout_below="#+id/logo"
android:layout_centerHorizontal="true" />
<com.petitchef.petitchef.views.customviews.CustomButton
android:id="#+id/button_sign_in"
android:layout_marginTop="20dp"
android:layout_width="180dp"
android:layout_height="35dp"
android:text="#string/sign_in_petitchef"
android:textColor="#color/flagWhite"
android:background="#drawable/petitchef_background_button"
android:layout_below="#+id/button_facebook_sign_in"
android:textSize="15sp"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="75dp"
android:src="#drawable/fork_and_knife"
android:layout_centerHorizontal="true" />
<include layout="#layout/signup_form"
android:id="#+id/sign_up_form"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="800dp"/>
<include layout="#layout/signin_form"
android:id="#+id/sign_in_form"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="800dp"/>
</RelativeLayout>
</RelativeLayout>
And the Java part
public class SignUpActivity extends AppCompatActivity {
private static final String TAG = "SignUpActivity";
View sliderView;
TextView switchToSignIn;
TextView switchToSignUp;
CallbackManager callbackManager;
EditText usernameSignIn;
EditText passwordSignIn;
EditText usernameSignUp;
EditText mailSignUp;
EditText passwordSignUp;
Button buttonSignIn;
Button buttonFacebook;
Button buttonConfirmSignIn;
Button buttonConfirmSignUp;
LoginButton loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login_signup);
//Testing if user already logged in
callbackManager = CallbackManager.Factory.create();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
if (sharedPref.contains(this.getString(R.string.token_shared_string))) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
sliderView = findViewById(R.id.slider_layout);
loginButton = (LoginButton) findViewById(R.id.button_facebook_sign_in);
loginButton.setReadPermissions("email");
buttonSignIn = (Button) findViewById(R.id.button_sign_in);
buttonSignIn.setTransformationMethod(null);
buttonConfirmSignIn = (Button) findViewById(R.id.button_confirm_sign_in);
buttonConfirmSignIn.setTransformationMethod(null);
buttonConfirmSignUp = (Button) findViewById(R.id.button_confirm_sign_up);
buttonConfirmSignUp.setTransformationMethod(null);
switchToSignIn = (TextView) findViewById(R.id.switch_to_login_text);
switchToSignIn.setText(Html.fromHtml(getString(R.string.signup_switch_to_signin)));
switchToSignUp = (TextView) findViewById(R.id.switch_to_signup_text);
switchToSignUp.setText(Html.fromHtml(getString(R.string.signin_switch_to_signup)));
switchToSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findViewById(R.id.sign_up_form).setVisibility(View.INVISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.VISIBLE);
}
});
switchToSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findViewById(R.id.sign_up_form).setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.INVISIBLE);
}
});
usernameSignIn = (EditText) findViewById(R.id.username_sign_in);
passwordSignIn = (EditText) findViewById(R.id.password_sign_in);
usernameSignUp = (EditText) findViewById(R.id.username_sign_up);
mailSignUp = (EditText) findViewById(R.id.mail_address_sign_up);
passwordSignUp = (EditText) findViewById(R.id.password_sign_up);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Resources resources = SignUpActivity.this.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
sliderView.animate()
.translationY(-0.8f * displayMetrics.heightPixels / 2)
.setDuration(600)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
findViewById(R.id.sign_up_form).setVisibility(View.INVISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.VISIBLE);
buttonSignIn.animate().alpha(0.0f)
.setDuration(300);
buttonSignIn.setEnabled(false);
loginButton.animate().alpha(0.0f)
.setDuration(300);
loginButton.setEnabled(false);
}
#Override
public void onAnimationEnd(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
});
buttonConfirmSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(usernameSignIn.getText()) || TextUtils.isEmpty(passwordSignIn.getText()))
Toast.makeText(SignUpActivity.this, getResources().getString(R.string.error_field_empty), Toast.LENGTH_SHORT).show();
String username = usernameSignIn.getText().toString();
String password = passwordSignIn.getText().toString();
APIManager.getInstance().login(username, password, new APIListener<Boolean>() {
#Override
public void onResult(Boolean hasSignUpSucceeded) {
if (hasSignUpSucceeded) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(SignUpActivity.this,
getResources().getString(R.string.error_password_or_username),
Toast.LENGTH_LONG)
.show();
}
}
});
}
});
buttonConfirmSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(usernameSignUp.getText()) || TextUtils.isEmpty(passwordSignUp.getText()) || TextUtils.isEmpty(mailSignUp.getText()))
Toast.makeText(SignUpActivity.this, getResources().getString(R.string.error_field_empty), Toast.LENGTH_SHORT).show();
String username = usernameSignUp.getText().toString();
String password = passwordSignUp.getText().toString();
String mail = mailSignUp.getText().toString();
APIManager.getInstance().register(username, password, mail, new APIListener<Boolean>() {
#Override
public void onResult(Boolean hasSignUpSucceeded) {
if (hasSignUpSucceeded) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(SignUpActivity.this,
getResources().getString(R.string.error_password_or_username),
Toast.LENGTH_LONG)
.show();
}
}
});
}
});
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
public void onBackPressed() {
usernameSignIn.setText("");
usernameSignIn.clearFocus();
passwordSignIn.setText("");
passwordSignIn.clearFocus();
usernameSignUp.setText("");
usernameSignUp.clearFocus();
mailSignUp.setText("");
mailSignUp.clearFocus();
passwordSignUp.setText("");
passwordSignUp.clearFocus();
sliderView.animate()
.translationY(0)
.setDuration(600)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
buttonSignIn.animate().alpha(1.0f)
.setDuration(300);
buttonSignIn.setEnabled(true);
loginButton.animate().alpha(1.0f)
.setDuration(300);
loginButton.setEnabled(true);
}
#Override
public void onAnimationEnd(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
I tried android:windowSoftInputMode="stateAlwaysHidden|adjustResize", I treid to put everything in a ScrollView (It just breaks the whole view)

NullPointerException when trying to open ZXingScannerView

I'm new to Android development so please bear with me.
I have the code inside an activity that implements qr scanning. Basically there is an activity before this segments of codes, but its just clicking of a button to go here. and whenever I do that, my app crashes and that is the error that returns. The idea of the app is once the user click the button, it will first display a qr scanner, once it has been scanned, it will now call this XML File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/scanbg"
tools:context=".ScanActivity">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="62dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question Here"
android:textSize="22dp"
android:id="#+id/questionhere"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/questionhere"
android:hint="Answer"
android:id="#+id/answerhere"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct or not indicator"
android:id="#+id/indicator"
android:layout_below="#id/answerhere"
android:textSize="18dp"/>
<!--this textview will be programmed to be changed as correct or not-->
<!--if answer == correct then "correct!" else "wrong answer"-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Point(s):"
android:id="#+id/userpoints"
android:layout_below="#id/indicator"
android:textSize="18dp"/>
<Button
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/userpoints"
android:layout_alignParentEnd="true"
android:text="Go"
android:textSize="14dp"
android:background="#B0DAD5"
android:id="#+id/gosagot"/>
</RelativeLayout>
and Here is the java file
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Button validateanswer;
ProgressDialog progress;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
validateanswer = (Button)findViewById(R.id.gosagot); //Im having error here
validateanswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
EditText theanswer = (EditText)findViewById(R.id.answerhere);
String sagotdito = theanswer.getText().toString();
RequestFactory.confirmanswer(ScanActivity.this, sagotdito, new RequestCallback<Boolean>() {
#Override
public void onSuccess(Boolean response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
//load new question
progress.dismiss();
}
});
}
#Override
public void onFailed(String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScanActivity.this, "Wrong Answer. Try Again!", Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
continuation...
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
Log.w("handleResult",result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText answertoQuestion = new EditText(this);
answertoQuestion.setHint("answer");
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setContentView(R.layout.activity_scan);
TextView j = (TextView)findViewById(R.id.questionhere);
EditText k = (EditText)findViewById(R.id.answerhere);
String n = k.getText().toString();
j.setText(result.getText());
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
please help me.
If you check the examples of ZXing...
In your activity XML, you can add a region for the QR scanner.
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Grab that and add the scanner view there.
public class ScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_simple_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
contentFrame.addView(mScannerView);
}
Your error is that you can't findViewById on your button when you replaced the content view with some other view that doesn't have the ID you want to find.
And even if you "switched" findViewById and setContentView around, your code wouldn't crash, but you would no longer have a button in the content view, so having the click action would be pointless.
The problem is that the button is a part of activity_scan and you set setContentView(mScannerView) to other layout.You are bound to get this error as the activity does not have a refernce to the view(button) you are refering.
What you can do is make the mScannerView a part of your main layout and then get it with findViewById();

Android Shared Preferences not working when relaunch app

I have 4 activities: MainActivity, p1, p2, p3.
My app works fine but problem here is that when app force stop or flick up app in home button to close, when the app is opened again, seems shared performance is cleared and my resume button just exit from app .
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
final Button resume = (Button) findViewById(R.id.resume);
Button next = (Button) findViewById(R.id.next);
Button exit = (Button) findViewById(R.id.exit);
resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
resume.setEnabled(false);
Log.d("Comments", "First time");
settings.edit().putBoolean("my_first_time", false).commit();
}else
{
MainActivity.this.finish();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, p1.class);
startActivity(intent);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
Xml :
<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:text="resume"
android:layout_width="wrap_content"
android:id="#+id/resume"
android:layout_height="wrap_content" />
<Button
android:text="next"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="exit"/>
</LinearLayout>
p1:
public class p1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.p1);
Button next = (Button) findViewById(R.id.next);
Button home=(Button)findViewById(R.id.home);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, p2.class);
startActivity(intent);
}
});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, MainActivity.class);
startActivity(intent);
}
});
}
private void storeCurrentActivity(){
SharedPreferences myPref =getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=myPref.edit();
editor.putString("lastactivity", p1.this.getClass().getSimpleName());
editor.commit();
}
#Override
public void onResume(){
super.onResume();
storeCurrentActivity();
}
}
XML:
<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:text="next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="page 1"/>
<Button
android:text="go in main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home"/>
</LinearLayout>
and p2, p3 like p1.
I have experiences in non-shared only but 0 may is a wrong flag!
getSharedPreferences(PREFS_NAME, 0); <-- Please use the Constant Context.MODE_WORLD_READABLE
Analysis:
once you have pressed the resume button it is stored as setting["MyPrefsFile", "my_first_time"] = true and resume-button is disabled in current activity instance.
when the activity gets destroyed and is recreated the resumebutton is not initialized from the settings so it is enabled.
to fix add this to you onCreate
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0)
resume.setEnabled(settings.getBoolean("my_first_time", true));

Categories