Android Change widget button - android

i've created my first widget but i've a problem when i change the button image.
below it's a part of code of java file for widget:
#Override
public void onReceive(Context context, Intent intent)
{
if (mp == null){
mp = MediaPlayer.create(context.getApplicationContext(), R.raw.segno);
}
final String action = intent.getAction();
if (ACTION_WIDGET_RECEIVER.equals(action)) {
if (mp.isPlaying()){
mp.stop();
mp.release();
mp = MediaPlayer.create(context.getApplicationContext(), R.raw.segno);
}
else{
RemoteViews control = new RemoteViews(context.getPackageName(), R.layout.widget);
control.setImageViewResource(R.id.button, R.drawable.pausa);
ComponentName cn = new ComponentName(context, Widget.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, control);
mp.start();
}
super.onReceive(context, intent);
}
super.onReceive(context, intent);
}
I read in the log this:
02-17 23:46:57.042: W/AppWidgetHostView(946): updateAppWidget couldn't find any view, using error view
I think this is a problem but i don't understand how resolve it.
when appear this error the widget say: Problem loading widget.
Thank you all
This is a XML Layout for widget
<?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:gravity="center"
android:layout_margin="4dp">
<Button
android:id="#+id/button"
android:paddingRight="30dp"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/vai" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/button"
android:maxHeight="100dp"
android:maxWidth="100dp"
android:src="#drawable/segno" />
</RelativeLayout>

you are trying to change the image of a Button which doesn't have the properties of Button according to this setImageViewResource is equivilant to ImageView properties so Instead of having a button I suggest you change it either to ImageButton or to ImageView that is clickable.
so maybe your XML will look like this:
<ImageButton
android:id="#+id/button"
android:paddingRight="30dp"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/vai" />
Update
the reason is that android:background is different than android:src it doesn't resize the photo it actually make the image as size of the photo (setImageViewResource is same as src) .. so you have either to resize the photo from the beginning or try to add this attribute to your ImageButton
android:scaleType="fitXY"
but I am not sure it will work, haven't tried it.
hope this works for you. try it out and give me a feedback.

Related

startActivity from BroadcastReceiver Button Views on Activity don't show up

I start my activity alarmAlert.class from onReceive().
The activity was started .
There three buttons and two TextViews on my activity.
when the activity started ,Textviews always show up,
but the buttons not always show up.
I start the activity from my MainActivity ,all the views work
perfect
Anything I can do .
thanks
I got something.
If my App is not running in background (click menu button,remove the app from list)
the activity started from onReceive() , buttons will not show up.
if the App still run in background ,everything is perfect .
my onReceive code:
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int id = intent.getIntExtra("id", -1);
try{
Intent alertIntent=new Intent();
alertIntent.setClass(context, AlarmAlert.class);
Bundle bundle=new Bundle();
bundle.putInt("id", id);
alertIntent.putExtras(bundle);
alertIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
context.startActivity(alertIntent);
}
catch (Exception e){
AlarmGloble.writeLog(context,"AlarmReceiver:"+e.toString());
}
part of my AlarmAlert code
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.d("AA","onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm_alert);
AlarmGloble.dbHelper=new DBHelper(this,AlarmGloble.DB_NAME,AlarmGloble.DB_VERSION);
AlarmGloble.dbLib=new DataBaseLib(AlarmGloble.dbHelper);
settingFromId();
findViews();
setListener();
updateView();
mVibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
setSystemVolume(0);
//play mp3 by Handler
mHandler.sendMessage(mHandler.obtainMessage(PLAY));
}
private void updateView(){
TextView textViewSnooze=(TextView)findViewById(R.id.alarm_alertTextViewSnooze);
if (mp3Test){
textViewSnooze.setVisibility(View.INVISIBLE);
spinnerSnooze.setVisibility(View.INVISIBLE);
buttonClose.setVisibility(View.INVISIBLE);
buttonEdit.setVisibility(View.INVISIBLE);
}
else {
textViewSnooze.setVisibility(View.VISIBLE);
spinnerSnooze.setVisibility(View.VISIBLE);
buttonClose.setVisibility(View.VISIBLE);
buttonEdit.setVisibility(View.VISIBLE);
if(alarmRept<=0){
textViewSnooze.setVisibility(View.VISIBLE);
spinnerSnooze.setVisibility(View.VISIBLE);
}
else{
textViewSnooze.setVisibility(View.INVISIBLE);
spinnerSnooze.setVisibility(View.INVISIBLE);
if (alarmReptCount<alarmReptTimes)
if (alarmKind==0)
mMessage=mMessage+"\n"+"next alarm :"+mClockSnooze[alarmRept]+" ";
else
mMessage=mMessage+"\n"+"next alarm:"+AlarmGloble.rept[alarmRept]+" ";
}
}
textViewMessage.setText(mMessage);
if(mMp3.equals(AlarmGloble.RANDOM)){
File file=new File(AlarmGloble.ROOT_MUSIC);
RandomMp3 rm=new RandomMp3(file);
if (rm.getCount()>0)
mMp3=rm.getFile();
else
mMp3="";
}
else {
if(mMp3.equals(AlarmGloble.DEFAULT)){
mMp3=getDefaultMP3();
}
else{
String[] s=mMp3.split("/");
textViewSongName.setText(s[s.length-1]);
}
}
if (mMp3.equals("")){
textViewSongName.setText(mMp3);
}
else {
String[] s=mMp3.split("/");
textViewSongName.setText(s[s.length-1]);
}
(LinearLayout)findViewById(R.id.alarm_alertLinearLayoutButtons);
linearLayoutButtons.requestFocus();
}
here is alarm_alert.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"
android:id="#+id/linearLayoutAlarmAlert" >
<LinearLayout
android:id="#+id/alarm_alertLinearLayoutButtons"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/alarm_alertButtonClose"
style="#style/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnClose" />
<Button
android:id="#+id/alarm_alertButtonEdit"
style="#style/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnEdit"
android:visibility="visible" />
<Button
android:id="#+id/alarm_alertButtonDismiss"
style="#style/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnExit"
android:visibility="visible" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/alarm_alertTextViewSnooze"
style="#style/RedLeft17sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/snooze" />
<Spinner
android:id="#+id/alarm_alertSpinnerSnooze"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<TextView
android:id="#+id/alarm_alertTextViewMessage"
style="#style/YellowLeft17sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/btnClose" />
<TextView
android:id="#+id/alarm_alertTextViewSongName"
style="#style/YellowLeft17sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:text="#string/btnClose" />
</LinearLayout>
I can only see 2 buttons buttonClose and buttonEdit in the AlarmAlert Activity, so i'm assuming the 3 buttons that aren't showing are in alarm_alertLinearLayoutButtons.xml which should be reused in alarm_alert.xml as such
<include layout="#layout/alarm_alertLinearLayoutButtons"/>
Ref: http://developer.android.com/training/improving-layouts/reusing-layouts.html
I can't see anything wrong with this except for the last couple of lines.
linearLayoutButtons isn't set.
linearLayoutButtons = (LinearLayout)findViewById(R.id.alarm_alertLinearLayoutButtons);
linearLayoutButtons.requestFocus();

Android: Unable to Prevent buttons from increasing size and overlapping with other buttons

I am new to Android Programming, what I am trying to do in this Android Application is to create a xml page filled with buttons.
When I click the button, the button would change to light green color and when I click it again, it would change to light grey
The error: I am getting is when I click the button, it increases in size and overlaps with the other buttons, please help me out here, it is not user friendly in this case
attached below is the code:
lockerbooking.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/sisButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="28dp"
android:text="#string/sis"
/>
<Button
android:id="#+id/solButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/soeButton"
android:layout_alignBottom="#+id/soeButton"
android:layout_alignParentRight="true"
android:text="#string/sol" />
<Button
android:id="#+id/soeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/sisButton"
android:layout_alignBottom="#+id/sisButton"
android:layout_centerHorizontal="true"
android:text="#string/soe" />
</RelativeLayout>
Code:
makeBooking.java
public class makeBooking extends Activity {
Button sisButton;
Button solButton;
Button soeButton;
Button sobButton;
super.onCreate(savedInstanceState);
// Get the message from the intent
setContentView(R.layout.lockerbookpage);
Intent intent = getIntent();
// Initialize TextViews
sisButton = (Button) findViewById(R.id.sisButton);
solButton = (Button) findViewById(R.id.solButton);
soeButton = (Button) findViewById(R.id.soeButton);
sobButton = (Button) findViewById(R.id.sobButton);
}
public OnClickListener solButtonListener = new OnClickListener(){
boolean flag = true;
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(flag){
solButton.setBackgroundColor(Color.GREEN);
}
else{
solButton.setBackgroundColor(Color.LTGRAY);
}
flag=!flag;
}
};
...The code goes on
Please help me out here, I am eager to learn
to avoid overlapping of buttons, use fixed width and height for buttons:
change this:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
to some this like this:
android:layout_width="100dp" //what ever size suits your layout
android:layout_height="50dp" //fixing this,will not overlap the buttons

What's wrong with this code of changing background of an imagebutton?

I am trying to change the image of an imagebutton using the following codes. Eclipse crashes but there is no error discoveredā€¦ I've also used setBackgroundResource instead of setImageResource, but it didn't work. Nothing in Logcat, nither in errors. Please help me to find the right way.
I have two images for this imagebutton. - edit_on & edit_off
xml
Java
imageblockButton = (ImageButton)findViewById(R.id.buttonblock);
imageblockButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageblockButton.setImageResource(R.drawable.edit_on);
Intent intent1 = new Intent (context, ActivityBlockList.class);
startActivity(intent1);
v.setClickable(true);
}
});
my xml looks likeā€¦
<ImageButton android:id="#+id/buttonblock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0sp"
android:scaleType="centerCrop"
android:background="#drawable/edit_off" />
In your xml
<ImageButton android:id="#+id/buttonblock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0sp"
android:scaleType="centerCrop"
android:src="#drawable/edit_off" />
use src instead of background
and
ImageButton btn = (ImageButton)findViewById(R.id.buttonblock);
btn.setImageResource(R.drawable.newimage);
Try this
imageblockButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.edit_on));

Android toggle button display wrong value after orientation change

Here is my problem.
I've got a simple activity which set a layout, and add rows in a table-layout(itself in a scroll view).
Those table-rows have a custom layout with a text-field and a toggle button.
Each toggle button has a value taken from a database, and when I first create the activity, the values are OK. But when I turn the device and then change the orientation, all the toggles-button take "false" value. I printed the values that I set in the Logcat, and the values are the good ones (those in the database).
I thought something like the layout I want is hidden behind another layout, but I made some tests and the text-fields change with new values, so I really don't understand why the toggle buttons don't work.
Here is the code :
TableRow layout :
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<RelativeLayout
android:id="#+id/relativelayout_row_parametres"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_weight="1.0">
<TextView
android:id="#+id/textview_row_parametres"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginLeft="2dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
/>
<ToggleButton
android:id="#+id/togglebutton_row_parametres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="2dp"
android:textOn="#string/togglebutton_on"
android:textOff="#string/togglebutton_off" />
</RelativeLayout>
</TableRow>
Activity Layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView style="#style/header" />
<LinearLayout
android:layout_width="fill_parent" android:layout_height="0dp"
android:layout_weight="0.8"
android:background="#drawable/gradient_bg"
android:padding="10dip"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent" android:layout_height="0dp"
android:layout_weight="0.85"
android:fillViewport="true"
android:padding="10dip"
android:layout_gravity="center">
<TableLayout
android:id="#+id/tablelayout_parametres"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/cornered_bg"
android:paddingTop="5dip"
android:paddingBottom="5dip">
</TableLayout>
</ScrollView>
<Button
android:id="#+id/button_parametres_accept"
android:gravity="center"
android:text="#string/accept_changes"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.15"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
And the activity code:
public class Parameters extends Activity {
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Map<String, Boolean> changes = new HashMap<String, Boolean>();
final Context ctx = getApplicationContext();
LanguageManager.updateConfig(this);
setContentView(R.layout.parametres);
CountryDB[] countries = Database.instance(getApplicationContext()).getCountries();
TableLayout tabLayout = (TableLayout) findViewById(R.id.tablelayout_parametres);
for(int i =0; i<countries.length; i++){
TableRow newRow = (TableRow) getLayoutInflater().inflate(R.layout.row_parametres, null);
TextView textView = (TextView) newRow.findViewById(R.id.textview_row_parametres);
ToggleButton toggleButton = (ToggleButton) newRow.findViewById(R.id.togglebutton_row_parametres);
toggleButton.setChecked(countries[i].isToSynchronize());
toggleButton.setTag(countries[i]);
Log.e("setChecked",""+toggleButton.getId()+"/"+countries[i].isToSynchronize());
textView.setText(countries[i].getLabel());
toggleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CountryDB countryTemp = (CountryDB) v.getTag();
changes.put(countryTemp.getLabel(), ((ToggleButton)v).isChecked());
}
});
tabLayout.addView(newRow);
TableRow rowDivider = (TableRow) getLayoutInflater().inflate(R.layout.row_divider, null);
tabLayout.addView(rowDivider);
}
Button buttonValidation = (Button) findViewById(R.id.button_parameters_accept);
buttonValidation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Iterator<String> iterator = changes.keySet().iterator();
while(iterator.hasNext()){
String stringTemp = iterator.next();
Database.instance(ctx).updateCountry(stringTemp, changes.get(stringTemp));
}
Intent intent = new Intent(ctx, Splash.class);
String result = "restart";
String from = "parameters";
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
returnIntent.putExtra("from", from);
setResult(RESULT_OK, returnIntent);
startActivity(intent);
}
});
}
}
In the Log.e, I print the values, and they are good, the display on togglebuttons is wrong, they are just all "false".
Thanks for your help.
Between onCreate() and onResume() , Android tries to restore the old state of the toggle Buttons. Since they don't have unique ID's , Android wont succeed and everything is false again. Try to move your setChecked() calls into onResume() ( maybe onStart() works too).
Here is a pretty good answer to the same Question:
ToggleButton change state on orientation changed
you have to save data before Orientation.
Android have method onSaveImstamceState(Bundle outState) and onRestoreInstanceState(BundleInstaceState)
override these method in Activity.
There's a simpler solution: you only need to add configChanges property to your activity declaration, like stated here. This way you can prevent Activity restart when orientation changes. So in your manifest you should have something like
<activity android:name=".Parameters"
android:configChanges="orientation|keyboardHidden">
or if your buildTarget>=13
<activity android:name=".Parameters"
android:configChanges="orientation|keyboardHidden|screenSize">
Edit: Like reported on comments below, this is not an optimal solution. The main drawback is reported in a note of the document linked above:
Note: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

Remove unnecessary margins from a custom dialog

I have a problem that I am designing a custom dialog for this. I am creating a xml for this as Framelayout is the root layout, and another framelayout with a gray background image is used for the contents, in which I have added a textview and two buttons Ok and Cancel and use all of this through dialog.setContentView(desired Xml Resource);
But when I generate that particular dialog then it shows extra spaces from each side, or we can say that extra margins are there but I don't know how it will removed? Please review the image attached with this question and suggest me the right solution.
Xml Layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content">
<FrameLayout android:id="#+id/rel"
android:layout_gravity="center_vertical" android:background="#drawable/dialog_box_bg" android:layout_width="wrap_content" android:layout_height="189dp">
<TextView android:id="#+id/tv_LogoutDialog_Text"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#424242"
android:text="Are you sure want to logout?" android:textSize="20dip" android:layout_gravity="center_vertical|center_horizontal"></TextView>
<Button android:id="#+id/btn_LogoutDialog_Cancel" android:background="#drawable/dialog_cancel_btn"
android:layout_marginLeft="20dip" android:layout_width="120dip" android:layout_height="42dip" android:layout_gravity="bottom|left" android:layout_marginBottom="15dip"></Button>
<Button android:id="#+id/btn_LogoutDialog_Ok"
android:background="#drawable/dialog_ok_btn_hover"
android:layout_width="120dip"
android:layout_height="42dip" android:layout_marginLeft="180dip" android:layout_gravity="bottom|right" android:layout_marginBottom="15dip" android:layout_marginRight="20dip"></Button>
</FrameLayout>
</FrameLayout>
Code:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
dialog = new Dialog(HomeScreenActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.logoutdialog);
btn_cancel = (Button)dialog.findViewById(R.id.btn_LogoutDialog_Cancel);
btn_ok = (Button)dialog.findViewById(R.id.btn_LogoutDialog_Ok);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dismissDialog(0);
}
});
btn_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(HomeScreenActivity.this,LoginScreen.class);
startActivity(intent);
}
});
return dialog;
}
return null;
}
Thanks in advance.
Don't use
dialog.setContentView(R.layout.logoutdialog);
use
LayoutInflater class to set Dialog content view
Here is link (Check) you can get the idea May this helps you.
Change it by adding a parameter false like in the code below.
dialog.customView(R.layout.dialog_blueprint, false)
The second argument (false) is wrapTheDialogBoxInScrollView. If the content in the dialog box is small and does not require a ScrollView set it to false.

Categories

Resources