Replacing button with imagebutton - android

So I am working on some code that a friend has left me (I have very little knowledge on this stuff) and have a question regarding Buttons and ImageButtons;
This code is for an app that requires you to click the 'connect' button to enter into a list of bluetooth devices. Once selected you are returned to the home screen and the button now says 'Disconnect'.
Basically, what I want to do is change it from a text based button to an Image button so that I can have a bluetooth icon (black) and when connected change to a connected bluetooth icon (white).
I have the icons and I understand the basic workings for a typical button however this code is a bit much for me. Any help would be greatly appreciated!
I have attached the initial sample of java for reference. The btnConnectDisconnect is the name of the button that I wish to replace.
// Handler Disconnect & Connect button
btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBtAdapter.isEnabled()) {
Log.i(TAG, "onClick - BT not enabled yet");
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else if (btnConnectDisconnect.getText().equals("Connect")) {
//Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices
Intent newIntent = new Intent(UartActivity.this, DeviceListActivity.class);
startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
}
else if (btnConnectDisconnect.getText().equals("Disconnect")) {
//unpair
System.out.println("Disconnecting from peripheral");
pDeviceAddress = null;
editor.remove("address");
editor.commit();
System.out.println("Currently saved address: " + prefs.getString("address", null));
System.out.println("Currently saved address check: " + pDeviceAddress);
//disconnect from service
Thread thread = new Thread() {
#Override
public void run() {
try {
sleep(50);
mService.disconnect();
System.out.println("Disconnecting from service...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
if(mService == null){
System.out.println("Service disconnected!");
} else System.out.println("Service connected!");

Based on the code, I can see that the button's name is btnConnectDisconnect. So what you can do is go into the XML file where this button is put and first replace the button tag (<Button .../>) with <ImageButton..../>. You can then add android:src="#drawable/name_of_drawable", to the ImageButton tag, to set the image you want the ImageButton to have. Then go back into the code and change the type of btnConnectDisconnect from Button to ImageButton. This should get you to where you want to go without having to touch the code inside the OnClickListener.
Hope this helps!

To get your desired behavior, there are a few things you need to do.
Change the type from Button to ImageButton in your Java file (posted above)
Create a new XML file (btn_bluetooth.xml) in the res/drawable directory with the following contents, making sure you replace the image references:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#drawable/BLUETOOTH_CONNECTED_IMAGE_REFERENCE"
/>
<item
android:state_selected="false"
android:drawable="#drawable/BLUETOOTH_DISCONNECTED_IMAGE_REFERENCE""
/>
</selector>
Change the type from Button to ImageButton in your XML layout file (usually referenced in the onCreate or onCreateView method of your Java file (posted above)
When you establish or lose a bluetooth connection, simply call btnConnectDisconnect.setEnabled() with true or false

Related

How to implement short press & long press(or long hold) in android app effectively?

I am creating an android application wherein I have mentioned the phone number, email, website of the business similar to the screenshot of google maps as attached.
Just like in the g maps where
Single click makes an intent to the respective app (opens dialer with phone number copied) etc.
Long Click/Press & hold will copy the number to clipboard displaying a toast that "Phone number is copied to clicpboard".
Now I have set up the intents properly and they are working fine --> step-1 achieved.
When I try to display the toast using "OnLongClickListener" method it is taking quite some time to display the toast message. Is there any way we can speed this up or am I missing something or should I use some other alternative like onTouch() method?
(Stuck with this, yet to learn and try out copying to clipboard thing. Inputs in this regards are also welcome!)
In the g maps app, the toast message appears almost instantly on press & hold. So the same is to be achieved.
The code extract from MainActivity.java (The website, phone number, email id are text views with drawableLeft. And I found out that we cannot use setOnItemLongClick on TextView as it is only for ListView)
// This method is called when the website text view is clicked and opens the compnay website
public void openWebsite(View v) {
TextView textView = (TextView) findViewById(R.id.webURL_text_view);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent openWebsiteIntent = new Intent(Intent.ACTION_VIEW);
openWebsiteIntent.setData(Uri.parse("https://www.company.com"));
if (openWebsiteIntent.resolveActivity(getPackageManager()) != null) {
startActivity(openWebsiteIntent);
}
}
});
textView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
showMessage();
return true;
}
});
}
public void showMessage(){
Toast.makeText(this,"Information copied to Clipboard", Toast.LENGTH_LONG).show();
}
I am new to android development and just trying out something, so please be as elaborative as possible. Thank You.

Android: Load the activity after accessing the notification bar

if there is no internet means I'm not able to load web resources. For this reason I'm giving the toast like "Check internet connectivity". After this toast, user may enable the internet option at notification bar and comes back. When he comes back, i want to reload the activity. For this requirement, i tried
onWindowFocusChanged and onActivityReenter
override methods but these are not working properly
MyCode
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
Intent intent = new Intent(CommonActivity.this, OtherActivity.class);
startActivity(intent);
}
}
When I'm using above code, my activity reloading again and again
There is a solution which i know is not perfect but it will work.
Define a activity level veriable like this
Boolean isAlreadyFocused = false;
Then in your onFocusChanged method do like this.
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus && !isAlreadyFocused ){
isAlreadyFocused = true;
Intent intent = new Intent(CommonActivity.this,OtherActivity.class);
startActivity(intent);
}else{
isAlreadyFocused = false;
}
}
Check this and tell me if this does not work.
By fallowing another way (i got this idea when i saw the flipkart app) i solved this internet checking
I'm checking for the internet connection, if there is no internet means i'm redirecting to NoInternetActivity that's design looks like
When user clicks on Retry button means i'm again checking for internet. If internet was accessible means i'm allowing user to home page of my app otherwise i'm redirecting to the NoInternetActivity again

SDK Android : How to open Shutdown/Reboot dialog for the device

I'm new here.
I have a problem, i try to shutdown a 4.2.2 android device (not root).
I know that ACTION_SHUTDOWN not works with unroot device.
So i want to open the existing shutdown/reboot/airplane dialog, the same we get when we maintain the on/off button. Then the user just have to click shutdown button.
I try to create by this way, without result...
Intent intent = new Intent(Settings.ACTION_DISPLAY_SETTINGS); // or others settings
startActivity(intent);
Thanks,
The is no public sdk access to open the power button menu programatically.
This link has all the approches Here.Simulating power button press to display switch off dialog box
InputManager.getInstance().injectInputEvent(new InputEvent(KeyEvent.KEYCODE_POWER, keyCode), sync);
'sync' becomes either of these:
InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT
and you need
import android.hardware.input.InputManager;
This is untested, but puts you in the right direction, also bare in mind, functionality like this is NOT recommend.
failing that:
public static void simulateKey(final int KeyCode) {
new Thread() {
#Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyCode);
} catch (Exception e) {
Log.e("Exception when sendKeyDownUpSync", e.toString());
}
}
}.start();
}
and simply call it like
simulateKey(KeyEvent.KEYCODE_POWER);

how to work with sockets, activities and views?

I'm new to programming in android and I need help to build an application. I want two phones to connect to each other, one being the client and the other being the server. I want the client to have 2 stages. In the first the user would input the ip of the server y click on a button to stablish the connection. In the second one the user would input a message and click on a button to send it to the server.
The code shown bellow is to send the string "message" to the server but as I was saying I want the user to be able to input the string. I don't know how to tackle his issue, do I need a second activity to be called once the connection is established in the activity I show bellow? In that case I wouldn't know how to pass a socket to another activity, I only know how to pass strings. Besides, I would need another button and therefore a new OnClickListener and I would still need to pass the socket to that function.
Without using a second activity I don't know how to make the second input field (the one where the user would input the message to send to the server) to show up once the connection is established. The views (layout.xml) for this activity are already associated to the same, I can't just clear the screen and create a new EditText field on the fly.
I hope I made myself clear.
Thanks in advance
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
**out.println("messageToSend");**
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
I don't think , you need a second activity to send message over socket.
Anyways , It depends on you design --
you can have two editTexts at a same but their visibility would be different.
EditText serverIpAddressET;
EditText messageET ; // Deafult visibility Gone
serverIpAddressET can be visible when user has not provided socket IP.
Once connection is established , you can change the visibility of serverIpAddressET to the Gone and make Visible the messageET .
Well a quick fix would be to hide the currently Displayed EditText and Button via
view.setVisiblility(View.GONE)
and display the other editText and button via
view.setVisibility(View.Visible)
and use same activity...
But a better solution would be to open the socket for communication in a service look in to android Service with Sockets... start the service in first activity and when connection is established shift too second activity and bind the activity with service so there can be communication btw activity and service...
Not entirely sure what you're looking for here but if I understand correctly you are woundering how to send a message. Simply add
message2send= (EditText) findViewById(R.id.user_message);
and then where you have
**out.println("messageToSend");**
replace with
**out.println(message2send);**
and add an extra edit text field to your layout.
It should be noted that the way you've gone about this is not ideal as the other phone (server) would have to be listening to the socket in order to receive the message which would cause additional data charges as well as wasting battery power (traditonal in mobile a server is between the 2 phones to store the message in case user if offline or phone is dead)
Hope this helps non the less!

Change ImageView image inside onClick event

I have an ImageView working as a button in my program. I need it to be an ImageView since I want just the image to be shown, not the borders.
This button is a lamp, if the data in database says it's visible, the lamp must be "on", when you click the button, it will check the data from bank and change it to "off" if it's on and vice-versa.
So, the change of image will happen inside a onClick event.
Here is my code:
btnVisualizar.setClickable(true);
btnVisualizar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (visivelBanco.getText().equals("Y")) {
btnVisualizar.setImageResource(this.getResources().getIdentifier(
"drawable/visible_off", null, this.getPackageName()));
} else {
btnVisualizar.setImageResource(
this.getResources().getIdentifier("drawable/visible_on", null, this.getPackageName()));
}
} catch (Exception e) {
Toast.makeText(
getBaseContext(),
"Falha ao modificar visibilidade do item!",
Toast.LENGTH_SHORT).show();
}
}
});
However the compiler doesn't recognize the method getResources() and getPackageName().
What am I doing wrong?
Any help is appreciatted.
The this in there refers to the onClickListener.
Use [Activity].this instead of this, where [Activity] is the name of the Activity
try
String uri = "drawable/visible_off"
btnVisualizar.setImageResource(EdicaoActivity.this.getResources().getIdentifier(uri, "drawable", EdicaoActivity.this.getPackageName()));
I think you just need to use the R class to obtain the identifier of your drawable. For example:
btnVisualizar.setImageResource(R.drawable.visible_on);
You should not need to go messing about with getResources().

Categories

Resources