With the help of onLongClickListener method one can use the button for two different purposes.
-------------This goes in the main.xml file--------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#018786"
android:gravity="center">
<Button
android:text="Hold me for a long time!"
android:id="@+id/lca_longClickBtn"
android:layout_marginTop="30dp"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
<TextView
android:id="@+id/lca_resultTV"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20dp"
android:textColor="#ffffff"/>
</LinearLayout>
----------------------------------------------------------
-----------------MyActivity.java file's content----------------
package com.app.yourappname;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class LongClickActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
private TextView tv;
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.long_click_activity);
tv = findViewById(R.id.lca_resultTV);
btn = findViewById(R.id.lca_longClickBtn);
btn.setOnClickListener(this);
btn.setOnLongClickListener(this);
}
@Override
public boolean onLongClick(View v) {
tv.setText("This is a LONG click!");
return true;
}
@Override
public void onClick(View v) {
tv.setText("This is a SIMPLE click!");
}
}
-------------------------------------------------------------
In the manifest, declare the Activity:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">
<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=".LongClickActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
No comments:
Post a Comment