Add a Button into PrefrenceScreen : Android - android

Hi i want to add a button into prefrencescreen, i got success into add a button into the prefrence but i could not get onClick event. i have attached my code a pic of prefence screen
setting.xml
<PreferenceCategory android:title="Application Details">
<Preference android:key="type"
android:title="Type"
android:summary="" />
</PreferenceCategory>
<PreferenceCategory android:title="Notification Settings">
<ListPreference android:key="sendNotificationType"
android:title="Status Notification For"
android:dialogTitle="Status Notification For" />
</PreferenceCategory>
settingdetail.xml
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textView2"
android:layout_marginLeft="15dp"
android:text="Type"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginLeft="15dp"
android:layout_toLeftOf="#+id/setFromTimeBtn"
android:text="Summary"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/buyItNowBtn"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
android:layout_centerVertical="true"
android:background="#drawable/button"
android:text="#string/buyItNowBtnTxt"
android:textColor="#color/white" />
and the onCreate Method of prefenceActivity Class
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.setting);
setContentView(R.layout.settingview);
Preference typePref = (Preference) findPreference("type");
typePref.setLayoutResource(R.layout.settingdetail);
typePref.setSelectable(true);
Button btn = (Button) findViewById(R.id.buyItNowBtn);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.e(TAG,"TEST");
Toast.makeText(Setting.this, "TEST", Toast.LENGTH_SHORT).show();
}
});
}
screenshot

This thread is stale, but since there is no solution yet, here is how I succeeded:
1. Set the button click listener
There are two ways to set the click listener for a button, either programmatically or via XML.
Programmatically: In your custom preference, override onBindView and attach the listener there:
#Override
protected void onBindView(View view) {
View button = view.findViewById(R.id.myButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "button click listener works!");
}
});
super.onBindView(view);
}
Via XML: Add android:onClick="yourMethodName" to the layout definition of the Button element (which is part of the layout for your preference, see below) and implement the method in your PreferenceActivityas described here: Responding to Click Events
2. Fix OnPreferenceClickListener
Now the button click listener should work, but the Preference's OnPreferenceClickListener will not work anymore. In order to fix this, add
android:descendantFocusability="blocksDescendants"
to the top element in the layout file for your preference:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:paddingEnd="?android:attr/scrollbarSize"
android:background="?android:attr/selectableItemBackground"
android:descendantFocusability="blocksDescendants">
<ImageView
android:id="#android:id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dip"
android:layout_marginEnd="6dip"
android:layout_marginTop="6dip"
android:layout_marginBottom="6dip"
android:layout_weight="1">
<TextView android:id="#android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:ellipsize="marquee"
android:fadingEdge="horizontal" />
<TextView android:id="#android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#android:id/title"
android:layout_alignStart="#android:id/title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="?android:attr/textColorSecondary"
android:maxLines="4" />
<Button android:id="#+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
<!-- Preference should place its actual preference widget here. -->
<LinearLayout android:id="#android:id/widget_frame"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" />
</LinearLayout>
(No android:onClick="yourMethodName" here as I chose to do it programmatically.)
3. Attach the Layout
Finally you need to set this layout to your preference XML file:
Add android:layout="#layout/myLayoutName" or alternatively set it via setLayoutResource as you construct the preference in your PreferenceFragment.

Implement OnPreferenceClickListener in preferenceActivity
private Preference mBuyPreference = null;
mLogoutPreference = findPreference(yourkey);
mBuyPreference.setOnPreferenceClickListener(this);
#Override
public boolean onPreferenceClick(Preference preference) {
if (preference == mBuyPreference) {
try {
//Do Something
}
return false;
}

Instead of using the onClick() handler, override the onPreferenceTreeClick method in your PreferenceActivity. There you will get the clicked preference object and you can check its key.
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference.getKey().equals("key")) {
// do something
return true;
}
return false;
}

I've solved half of your problem by creating a custom preference like this -
In order to get to this, I created a custom preference like this -
public class CustomPreference extends Preference {
private LinearLayout mWidgetContainer;
private View mRowView;
public CustomPreference(Context context) {
super(context);
}
public CustomPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected View onCreateView(ViewGroup parent) {
LayoutInflater viewInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRowView = viewInflater.inflate(R.layout.preferences_row_view, parent, false);
mWidgetContainer = (LinearLayout) mRowView.findViewById(android.R.id.widget_frame);
Button button = new Button(getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setBackgroundResource(R.drawable.listview_row_bg);
button.setTextSize(14);
button.setPadding(5, 5, 5, 5);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), BuyScreenActivity.class);
getContext().startActivity(intent);
}
});
button.setTypeface(null, Typeface.BOLD);
button.setText("Buy now");
mWidgetContainer.addView(button);
return mRowView;
}
}
Then in your settings xml file you can create a setting like
<package.of.your.java.file.CustomPreference
android:key="type"
android:title="Type"
android:summary="" />
And my preferences_row_view.xml is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="50dip"
android:paddingLeft="5dip"
android:paddingRight="?android:attr/scrollbarSize" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="6dip"
android:layout_marginRight="6dip"
android:layout_marginTop="6dip"
android:layout_weight="1" >
<TextView
android:id="#+android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:lineSpacingMultiplier="1.3"
android:textSize="14sp" />
<TextView
android:id="#+android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#android:id/title"
android:layout_below="#android:id/title"
android:maxLines="4"
android:textSize="13sp" />
</RelativeLayout>
<!-- Preference should place its actual preference widget here. -->
<LinearLayout
android:id="#+android:id/widget_frame"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="horizontal" />
</LinearLayout>
That will do.
But there is one more issue I'm facing which I've posted here on SO.
Add a button in Preference Row

Instead of
Button btn = (Button) findViewById(R.id.buyItNowBtn);
do this
Button btn = (Button)typePref.getView(view, viewGroup );

Related

Butter Knife - Listeners For Buttons inside include

I have simple Relative layout with one button.
And Im using this layout multiple times using include in Main Layout.
Its possible to write one method (using ButterKnife or not) for all this buttons using listener(this) and not creating multiple listeners like this ---->
(relativeLayout1.findViewById(R.id.currencyButton)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ForeignExchangeActivity.this, "Euro", Toast.LENGTH_SHORT).show();
}
});
(relativeLayout2.findViewById(R.id.currencyButton)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ForeignExchangeActivity.this, "GBP", Toast.LENGTH_SHORT).show();
}
});
Single item layaout
<?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/colorBackgroundSeekbar">
<TextView
android:id="#+id/currencyTitle"
android:text="EUR - PLN"
android:padding="5dp"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#color/colorButtonHiglight"/>
<TextView
android:id="#+id/currencyDate"
android:layout_below="#id/currencyTitle"
android:text="24-01-2015"
android:textStyle="bold"
android:layout_marginTop="12dp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/currencyValue"
android:layout_below="#+id/currencyDate"
android:text="4.4567"
android:layout_marginTop="12dp"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:textSize="25sp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorCalculatorActivity"/>
<TextView
android:text="Inna data"
android:textAllCaps="false"
android:layout_marginTop="10dp"
android:id="#+id/currencyButton"
android:textSize="12sp"
android:padding="5dp"
android:gravity="center"
android:layout_below="#id/currencyValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/button_rounder_corners"
android:layout_alignLeft="#+id/currencyValue"
android:layout_alignRight="#+id/currencyValue"
android:onClick="onClickDataButton"
/>
<View
android:layout_marginTop="10dp"
android:layout_below="#id/currencyButton"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</RelativeLayout>
Example Inlcude
<LinearLayout
android:layout_width="match_parent"
android:weightSum="2"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin">
<include
android:id="#+id/currency1"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
layout="#layout/single_item_foreign_exchange"/>
<View
android:layout_width="10dp"
android:layout_height="match_parent"/>
<include
android:id="#+id/currency2"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
layout="#layout/single_item_foreign_exchange"/>
</LinearLayout>
Binded inlcude layaouts
#Bind(R.id.currency1) RelativeLayout relativeLayout1;
#Bind(R.id.currency2) RelativeLayout relativeLayout2;
SOLVED
Added onClick method to my RelativeLayaout. Then created something like this
public void onClickDataButton(View view){
if (view == buttonEuro){
Toast.makeText(ForeignExchangeActivity.this, "Euro", Toast.LENGTH_SHORT).show();
} else if ( view == buttonGBP){
Toast.makeText(ForeignExchangeActivity.this, "GBP", Toast.LENGTH_SHORT).show();
}
}
And my button looks like
buttonEuro = (TextView) relativeLayout1.findViewById(R.id.currencyButton);
buttonGBP = (TextView) relativeLayout2.findViewById(R.id.currencyButton
);
so the same button id but finded in diffrent layaouts.
EDIT: Example for your case added: Buttons with same ID in different layouts.
1) You could iterate over an Array of Buttons.
2) Or: Create a custom Button-Class which holds anything custom you need (i.e. field for currency etc) and use that in your Layout.
Kind of Pseudocode (not tested):
class CurrencyButton extends android.widget.Button {
string currency;
public void init(Context ctx, String currency) {
this.currency = currency;
this.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ctx, this.currency, Toast.LENGTH_SHORT).show();
}
});
}
public void doSomeOtherFancyCurrencyLogicHere() {
....
}
}
This can be used in your Layout files: (Pseudo)
<your.package.CurrencyButton
id="#+id/currency_button_eur"
LayoutParams etc />
<your.package.CurrencyButton
id="#+id/currency_button_gbp"
LayoutParams etc />
<!-- EDIT: as in your example with layouts in single_item_foreign_exchange -->
<your.package.CurrencyButton
id="#+id/currency_button"
LayoutParams etc />
If you use Butterknife
#InjectView(R.id.currency_button_eur)
your.package.CurrencyButton buttonEUR;
#InjectView(R.id.currency_button_gbp)
your.package.CurrencyButton buttonGBP;
// ... initialize them somewhere
buttonEUR.init(this, "EUR");
buttonGPB.init(this, "GBP");
// EDIT: as in your example with layouts
((your.package.CurrencyButton) relativeLayout1.findViewById(R.id.currencyButton)).init(this, "EUR");
((your.package.CurrencyButton) relativeLayout2.findViewById(R.id.currencyButton)).init(this, "GBP");
Actually you could go even further and extend this class for each currency, but this should do it in the first place.
Ok, I've seen you have SOLVED your question. But since I was already working on this answer, I'll add it here anyway :P
class CurrencyLayout extends FrameLayout {
String currency;
// Constructors that calls init after super(...);
public void init(Context ctx, AtributeSet attrs) {
View includedLayout = LayoutInflater.fromContext(ctx).inflate(R.layout.single_item_foreign_exchange, this, false);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CurrencyLayout,
0, 0);
try {
final String currency = a.getString(R.styleable.CurrencyLayout_currencyName);
} finally {
a.recycle();
}
includedLayout.findViewById(R.id.currencyName).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ctx, this.currency, Toast.LENGTH_SHORT).show();
}
});
}
this.addView(includedLayout);
}
inside res/values/attrs.xml add something like this:
<resources>
<declare-styleable name="CurrencyLayout">
<attr name="currencyName" format="string" />
</declare-styleable>
</resources>
And inside your Activity layout:
<LinearLayout
android:layout_width="match_parent"
android:weightSum="2"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin">
<your_package.CurrencyLayout
android:id="#+id/currency1"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
custom:currencyName="GBP"/>
<View
android:layout_width="10dp"
android:layout_height="match_parent"/>
<your_package.CurrencyLayout
android:id="#+id/currency2"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
custom:currencyName="EUR"/>
</LinearLayout>
I hope this helps you anyway :D
More information on custom views and attributes

Android: How to catch click on any button in Linear Layout?

I have the following Layout:
<LinearLayout
android:id="#+id/group_button_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/group_button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Week"/>
<Button
android:id="#+id/group_button_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:padding="0dp"
android:text="Month"/>
<Button
android:id="#+id/group_button_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Quarter"/>
<Button
android:id="#+id/group_button_4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Half Year"/>
</LinearLayout>
I created the onClickListener on layout like that:
private void initViews() {
mGroupedButtonLayout = (LinearLayout) findViewById(R.id.group_button_layout);
}
private void initListeners() {
mGroupedButtonLayout.setOnClickListener(mButtonGroupListener);
}
And I thought that after click on a button onClick event will be triggered:
private View.OnClickListener mButtonGroupListener = new View.OnClickListener() {
public void onClick(View v) {
Logger.d("Clicked");
Logger.d(String.valueOf(v.getId()));
// do something when the button is clicked
}
};
Is it possible to catch onClick event on every button without the need to create a listener for each button?
You could set the android:onClick attribute for the buttons, and handle your logic in the method you point it to.
XML
<Button
android:id="#+id/group_button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Week"
android:onClick="doButtonClick"/>
Java
public void doButtonClick(View v) {
switch(v.getId()) {
case R.id.group_button_1:
//do whatever for this button
break;
default:
break;
}

how to get Android Custom Preference TextView OnClick?

I can't get custom preference TextView action. May I know how to get it.
Here my preference xml file user_setting.xml,
<PreferenceCategory android:title="#string/security_settings"
android:key="security">
<Preference
android:title="#string/change_pin"
android:summary="#string/change_pin_summary"
android:key="change_pin"
android:layout="#layout/test"/>
</PreferenceCategory>
Here my custom xml layout for preference test.xml
<?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="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:paddingLeft="7dp"
>
<TextView android:id="#android:id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:textSize="19dp"
/>
<TextView android:id="#android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#android:id/title"
android:layout_alignLeft="#android:id/title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:maxLines="2"
/>
</LinearLayout>
My activity is here,
public class AppPreference extends SherlockPreferenceActivity {
private boolean needResource=false;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (needResource || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
addPreferencesFromResource(R.xml.user_setting);
}
Initialize();
}
private void Initialize(){
Preference change_pin = findPreference("change_pin");
change_pin.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Toast.makeText(getBaseContext(), "PIN",
Toast.LENGTH_SHORT).show();
/* Intent myIntent = new Intent(AppPreference.this, OriginalPinActivity.class);
AppPreference.this.startActivity(myIntent);*/
return true;
}
});
}
It's not work when click or touch on this preference. Please pointing to me how to do it.

onclick event in dialog preference

I have a custom dialog preference that have bunch of button.each button represent a number.something like clock application when you want to set alarm. how can I get onClick of each button in my dialog preference?
this is part of my dialog layout (time_picker) :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<LinearLayout
android:id="#+id/showTimer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="_ _ : _ _"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>
<RelativeLayout
android:id="#+id/Buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_below="#+id/showTimer"
android:layout_marginTop="10dp">
<Button
android:id="#+id/button1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button5"
android:layout_alignBottom="#+id/button5"
android:layout_alignLeft="#+id/button3"
android:layout_centerInParent="true"
android:text="6"
android:textStyle="bold"
android:textSize="20dp"
android:tag="1"
android:background="#android:color/transparent" />
<Button
android:id="#+id/button2"
android:layout_width="100dp"
...
this is Setting layout that launch dialog preference:
<com.example.test.TimerForNoti
android:key = "pref_sync_noti_timer"
android:title = "#string/pref_sync_noti_timer"
android:summary = "#string/pref_sync_noti_timer_summ"
android:dialogMessage = "#string/pref_sync_noti_timer">
</com.example.test.TimerForNoti>
and this is class of dialog preference (TimerForNoti) :
public class TimerForNoti extends DialogPreference
{
public TimerForNoti(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.time_picker);
setPositiveButtonText(R.string.ok);
setNegativeButtonText(R.string.cancel);
Dialog di = new Dialog(context);
di.setContentView(R.layout.time_picker);
OnClickListener test = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String tag = v.getTag().toString();
if(tag == "1"){
Log.v("onOne", "ok");
}
// .....
}
};
Button btn1 = (Button) di.findViewById(R.id.button1);
btn1.setOnClickListener(test);
}
}
If I understand your question right, you can set tag for each button and set one OnClickListener for all of them:
<Button
android:id="#+id/button1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button5"
android:layout_alignBottom="#+id/button5"
android:layout_alignLeft="#+id/button3"
android:layout_centerInParent="true"
android:text="6"
android:textStyle="bold"
android:textSize="20dp"
android:tag="6"
android:background="#android:color/transparent" />
Code:
OnClickListener buttonsListener = new OnClickListener() {
#Override
public void onClick(View v) {
String buttonText = v.getTag().toString();
// your logic here
}
};
Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(buttonsListener);
Button btn2 = (Button)findViewById(R.id.button2);
btn2.setOnClickListener(buttonsListener);
Button btn3 = (Button)findViewById(R.id.button3);
btn3.setOnClickListener(buttonsListener);
// your buttons here
Also you can use v.getId() in OnClickListener for determining which button was clicked
As much I understood your question. You want one method to be called on every button clicked.
For that Add this to your every button element in xml:
<Button
android:onClick="OnClick"
.. />
And this method to your .java file where you want to perform task:
public void OnClick(View v){
// do something....
}
Or you can directly call setOnClickListener at button object
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// do something....
}
});

Using overlays for user instruction android

Hi im trying to add a simple overlay to my app to highlight bits and bobs to the user i am currently following this short guide
http://www.christianpeeters.com/android-tutorials/android-tutorial-overlay-with-user-instructions/
but i get an error using android studio cannot resolve variable topLeveLayout im a complete beginner and have tried alsorts to get this moving any suggestions?
here is my xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_layout" >
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="match_parent"
android:layout_height="55dp"
android:text="#string/bath2"
android:id="#+id/bath_text_View"
android:textSize="23sp"
android:gravity="center"
android:textStyle="bold|italic" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/bath_text_View"
android:contentDescription="#string/bathable2"
android:src="#drawable/pic5"
android:layout_above="#+id/nextbutton"
android:id="#+id/imageView"
android:scaleType="centerCrop"
android:cropToPadding="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
android:id="#+id/nextbutton"
android:textSize="20sp"
android:textStyle="bold|italic"
android:layout_gravity="center"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="nextImage2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:background="#android:color/transparent"
android:layout_above="#+id/button4"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/button4"
android:background="#android:color/transparent"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:clickable="false" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#88666666"
android:id="#+id/top_layout">
<ImageView
android:id="#+id/ivInstruction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:paddingTop="25dp"
android:layout_marginRight="15dp"
android:clickable="false"
android:paddingLeft="20dip"
android:scaleType="center"
android:contentDescription="#string/overlay"
android:src="#drawable/hint_menu" />
</RelativeLayout>
</FrameLayout>
So i have 2 relative layouts in a frame layout the first being my app and the second underneath being the overlay
here is my .java
public class bathactivity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bath_2);
topLevelLayout = findViewById(R.id.top_layout);
if (isFirstTime()) {
topLevelLayout.setVisibility(View.INVISIBLE);
}
Button button2 = (Button) findViewById(R.id.button2);
Button button4 = (Button) findViewById(R.id.button4);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(bathactivity2.this, R.raw.rubber_duck);
mp.start();
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(bathactivity2.this, R.raw.bubbles);
mp.start();
}
});
}
public void nextImage2(View view){
Intent intent = new Intent(this, BathActivity3.class);
startActivity(intent);
}
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
topLevelLayout.setVisibility(View.VISIBLE);
topLevelLayout.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
topLevelLayout.setVisibility(View.INVISIBLE);
return false;
}
});
}
return ranBefore;
}
}
it is just an image with a couple of hidden buttons on it hence the reason i would like an overlay to point out where the buttons are, i get errors cannot resolve topLevelLayout cannot resolve motion event and others, is it just a case of declaring these first and if so how? is it something like
Layout topLevelLayout;
or is there something worse going on here thank you for any help
View topLevelLayout;
this solved it

Categories

Resources