禁用按钮不在屏幕旋转上工作

时间:2018-04-13 04:32:18

标签: android android-lifecycle

我正在尝试制作一个Android应用程序,其中我有一个向服务器发送数据的按钮,我想在一次点击一段时间后(一天或几个小时)禁用按钮,我已经添加了代码这和那是正常的。 但是当我旋转屏幕时,按钮变为启用状态,当我将应用程序置于后台时,按钮再次启用。所以任何人都可以告诉我如何在任何条件下(屏幕旋转和放入背景)中的特定时间禁用该按钮。这是我的代码

 SendLocation = (Button) findViewById(R.id.btnp_send_data_to_server);
    if(user_name.equalsIgnoreCase(Hr)){
        SendLocation.setVisibility(View.INVISIBLE);
    }
    else {
        SendLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                    SendDataToServer(employeeId, lat, lon, username, timeStamp, mon,officeLocation, officeTimings);

                    SendLocation.setEnabled(false);
                    Timer buttonTimer = new Timer();
                    buttonTimer.schedule(new TimerTask() {

                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    SendLocation.setEnabled(true);
                                }
                            });
                        }
                    }, 1000 * 60 * 60);


                } else {

                    locationTrack.showSettingsAlert();
                }

            }
        });

    }





 <Button
    android:id="@+id/btnp_send_data_to_server"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:background="@drawable/button_bg"
    android:text="send location"
    android:padding="10dp"/>








 <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/AppTheme">
    <activity android:name=".LoginActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MainActivity" />
    <activity android:name=".ProfileActivity" />
    <activity android:name=".SqliteActivity" />
    <!-- <service android:name=".JobSchedulerService" -->
    <!-- android:permission="android.permission.BIND_JOB_SERVICE" -->
    <!-- android:exported="true"/> -->
    <!-- &lt;!&ndash; registering the receiver &ndash;&gt; -->
    <!-- <receiver -->
    <!-- android:name=".MyAlarm" -->
    <!-- android:enabled="true" -->
    <!-- android:exported="true" /> -->
    <activity android:name=".CheckAttendanceForEmployee" />
    <activity android:name=".CheckAttendanceForHR" />
    <activity android:name=".EmployeeAttendanceActivity" />
    <activity android:name=".HrAttendanceActivity" />
    <activity android:name=".TotalAttendanceActivity"></activity>
</application>

6 个答案:

答案 0 :(得分:0)

在表现形式中,请添加 android:configChanges 属性,以避免在旋转屏幕时出现问题。

 <activity
            android:name=".login.LoginActivity"
            android:configChanges="orientation|screenSize"
           />

如果您遇到任何问题,希望这对您有用,请告诉我。

答案 1 :(得分:0)

这是因为屏幕旋转再次调用活动(所有活动方法都会召回)。

 public abstract class AbstractActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}}

答案 2 :(得分:0)

全局创建一个static变量,表示计时器仍在运行,并在onCreate中使用它来禁用它,如

private static boolean isRunning = false; //initially

<强>的onCreate

SendLocation = (Button) findViewById(R.id.btnp_send_data_to_server);
SendLocation.setEnabled(!isRunning);

<强> onClickListener

 Timer buttonTimer = new Timer();
                isRunning = true;
                buttonTimer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                isRunning = false;
                                SendLocation.setEnabled(true);
                            }
                        });
                    }
                }, 1000 * 60 * 60);

答案 3 :(得分:0)

当屏幕方向改变时,Activity停止并重新创建(再次调用onCreate()方法),它会将Button的属性重置为默认值,这会使Button再次点击。

现在要解决此问题,您必须覆盖到Activity方法1. onSaveInstanceState()和2. onRestoreInstanceState()。

当屏幕方向改变时,onSaveInstanceState()方法调用第一个,在这里你必须保存你的Button状态,就像它可以点击一样。

在Activity重新创建调用的onRestoreInstanceState()方法之后, 在这里你可以恢复按钮状态。

@Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putBoolean(Btn_clickable, true);
    } 




 @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        savedInstanceState.getBoolean("Btn_clickable");
    }

答案 4 :(得分:0)

 boolean click = false; //initial value of click state

 button.setEnabled(click); // call this where you want to disable

 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putBoolean("click",click);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

     click = savedInstanceState.getBoolean("click");
     Log.d("click","clik "+click);
     button.setEnabled(click);
}

活动在saveOnInstanceState中保存实例的状态,并通过调用RestoreInstancestate将其返回到重新加载视图

  

块引用

答案 5 :(得分:0)

尝试以下说明性示例:

Demo14.class:----------

public class Demo14 extends AppCompatActivity{

private Button b;
private CheckBox cb;
private CheckBox cb1;
private SharedPreferences preferences;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo16);

    preferences = getSharedPreferences("preferences",0);

    cb = (CheckBox) findViewById(R.id.cb);
    cb1 = (CheckBox) findViewById(R.id.cb1);

    b = (Button) findViewById(R.id.b);

    cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            b.setEnabled(isChecked);
        }
    });

    }

//called on device orientation changes
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if(outState != null) {
        outState.putBoolean("cb", cb.isChecked());
        if (cb.isChecked()) {
            outState.putBoolean("cb1", cb1.isChecked());
            outState.putBoolean("b", b.isEnabled());
        } else {
            outState.putBoolean("cb1", true);// default case is true
            outState.putBoolean("b", true);// default case is true
        }
    }
}

//called after orientation is changed
@Override
protected void onRestoreInstanceState(Bundle savedState) {
    super.onRestoreInstanceState(savedState);
    if(savedState != null) {
        cb.setChecked(savedState.getBoolean("cb", false));
        cb1.setChecked(savedState.getBoolean("cb1", true));
        b.setEnabled(savedState.getBoolean("b", true));
    }
}

@Override
protected void onPause() {
    super.onPause();
    if(preferences != null){
        setBoolean("cb",cb.isChecked());
        if(cb.isChecked()){
            setBoolean("cb1",cb1.isChecked());
            setBoolean("b",b.isEnabled());
        }else{
            setBoolean("cb1",true);// default case is true
            setBoolean("b",true);// default case is true

        }
    }

}

@Override
protected void onResume() {
    super.onResume();
    if(preferences != null){
        cb.setChecked(preferences.getBoolean("cb",false));
        cb1.setChecked(preferences.getBoolean("cb1", true));
        b.setEnabled(preferences.getBoolean("b", true));
    }
}

   private void setBoolean(String preferenceName, boolean value)
{
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean(preferenceName, value);
    editor.apply();
}
}

demo16:XML:----------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enable/Disable Button"
    android:checked="true"
    android:id="@+id/cb1"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button"
    android:layout_marginStart="15dp"
    android:id="@+id/b"/>

</LinearLayout>

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save Button State"
    android:checked="false"
    android:id="@+id/cb"/>

</LinearLayout>