Hi there! Today we will be doing an interesting and easy task where we will be making the button to function without implementing our general onClickListener() method.
This is achieved by just adding one more attribute in the xml file and the button will listen to us.
Here we go....
-------------Our xml file will have the following-------------
This is achieved by just adding one more attribute in the xml file and the button will listen to us.
Here we go....
-------------Our xml file will have the following-------------
<?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="#F06292"
android:gravity="center">
<Button
android:text="Click"
android:id="@+id/button1"
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="80dp"
android:onClick="clicked"
android:textSize="25sp"
android:textStyle="bold"
android:textColor="#ffffff"
android:background="#EC407A"
android:layout_gravity="center"/>
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:background="#F8BBD0"
android:gravity="center"
android:textColor="#000000"
android:textStyle="bold"
android:textSize="25dp"
android:text=""/>
</LinearLayout>
------------------------------------------------------------------
-----------------The OnClickXmlAcivity.java code----------------------
package com.app.yourappname;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class OnClickXmlActivity extends AppCompatActivity {
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.on_click_xml_activity);
tv = findViewById(R.id.textView1);
}
public void clicked(View v) {
tv.setText("Clicked!");
}
}
-----------------------------------------------------
--------------------- In the manifest file declare activity name -------------------
<?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=".OnClickXmlActivity">
<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