2012-11-21 4 views
5

나는 비슷한 질문을하기 전에 물었습니다.하지만 나는 너무 애매했습니다. 아래 코드는 멋진 양식화 된 단추를 그립니다. 버튼을 클릭하면 숫자를 입력하고 숫자를 기준으로 배경색을 변경합니다.Android 위젯과 함께 setBackground 사용하는 방법

remoteViews.setInt (R.id.nmcButton, "setBackgroundColor", color);

불행하게도

, 내가

remoteViews.setInt (R.id.nmcButton, "setBackground의"색상)를 사용하여 스타일을 유지하려고;

위젯이로드되지 않습니다. 이 문제를 해결할 방법이 있습니까? 배경색을 변경하면서 스타일을 유지할 수있는 방법이 있습니까?

여기에 관련 파일

package test.widget; 

    import android.os.Bundle; 
    import android.app.PendingIntent; 
    import android.appwidget.AppWidgetManager; 
    import android.appwidget.AppWidgetProvider; 
    import android.content.ComponentName; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.util.Log; 
    import android.widget.RemoteViews; 
    import android.graphics.Color; 

    public class MyWidget extends AppWidgetProvider { 

     private final static String TEST_ACTIVITY = "test.widget.action.TEST_ACTIVITY"; 
     private final static int INTENT_NO_REQUEST = 0; /* no requestCode */ 
     private final static int INTENT_NO_FLAGS = 0; /* code for no Flags */ 
     private int count = 9; 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      super.onReceive(context, intent); 
      Bundle b = intent.getExtras(); 
      if (b != null) { 
       count = b.getInt("nmcCount"); 
       callOnUpdate(context); 
      } 
     } 

     private void callOnUpdate(Context context) { 
      AppWidgetManager appWidgetManager = AppWidgetManager 
        .getInstance(context); 
      ComponentName thisAppWidget = new ComponentName(
        context.getPackageName(), MyWidget.class.getName()); 
      int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget); 
      onUpdate(context, appWidgetManager, appWidgetIds); 
     } 

     @Override 
     public void onUpdate(Context context, AppWidgetManager appWidgetManager, 
       int[] appWidgetIds) { 
      super.onUpdate(context, appWidgetManager, appWidgetIds); 
      buildUpdate(context, appWidgetManager, appWidgetIds); 
     } 

     private void buildUpdate(Context context, 
       AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
      final int N = appWidgetIds.length; 
      for (int i = 0; i < N; i++) { 
       int appWidgetId = appWidgetIds[i]; 

       RemoteViews remoteViews = new RemoteViews(context.getPackageName(), 
         R.layout.widget); 

       Intent intent = new Intent(TEST_ACTIVITY); 
       PendingIntent pendingIntent = PendingIntent.getActivity(context, 
         INTENT_NO_REQUEST, intent, INTENT_NO_FLAGS); 
       remoteViews.setOnClickPendingIntent(R.id.nmcButton, pendingIntent); 
       remoteViews.setTextViewText(R.id.nmcButton, String.valueOf(count)); 

       // the code below works, but the button does not have nice styling 
       // int color = (count >= 5) ? Color.GREEN : Color.RED; 
       // remoteViews.setInt(R.id.nmcButton, "setBackgroundColor", color); 

       // this code doesn't work, you get "problem loading widget" 
       int color = (count >= 5) ? R.drawable.btn_green 
         : R.drawable.btn_red; 
       remoteViews.setInt(R.id.nmcButton, "setBackground", color); 

       appWidgetManager.updateAppWidget(appWidgetId, remoteViews); 
      } 
     } 
    } 

중 일부는

<?xml version="2.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android"> 

     <item android:state_pressed="true"><shape> 
     <solid android:color="#ef4444" /> 

     <stroke android:width="1dp" android:color="#992f2f" /> 

     <corners android:radius="3dp" /> 

     <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" /> 
    </shape></item> 
     <item><shape> 
     <gradient android:angle="270" android:endColor="#992f2f" android:startColor="#ef4444" /> 

     <stroke android:width="1dp" android:color="#992f2f" /> 

     <corners android:radius="3dp" /> 

     <padding android:bottom="11dp" android:left="10dp" android:right="10dp" android:top="10dp" /> 
    </shape></item> 

    </selector> 

styles.xml btn_red.xml 있습니다

공동 작업자가 대답을했다
<resources> 
     <style name="ButtonText"> 
      <item name="android:layout_width">wrap_content</item> 
      <item name="android:layout_height">wrap_content</item> 
      <item name="android:gravity">center</item> 
      <item name="android:layout_margin">1dp</item> 
      <item name="android:textSize">10dp</item> 
      <item name="android:textStyle">normal</item> 
      <item name="android:shadowColor">#000000</item> 
      <item name="android:shadowDx">1</item> 
      <item name="android:shadowDy">1</item> 
      <item name="android:shadowRadius">2</item> 
      <item name="android:textColor">#ffffff</item> 
     </style> 
     <style name="AppTheme" parent="android:Theme.Light" /> 
    </resources> 

답변

13

, 내가 사용해야 :

remoteViews.setInt(R.id.nmcButton, "setBackgroundResource", color); 
,

대신의 :

remoteViews.setInt(R.id.nmcButton, "setBackground", color); 
+0

작동하지 않습니다. 스타일이 제거되었습니다. 그것은 자신의 질문에 대답하지 않습니다 – AxeManTOBO

1

나는 나를 위해 작동하지 않았다하지만이 시도.

당신은 당신이해야 할 위젯의 색상 설정하려는 경우 : 이것은 내 위젯 내 ListView에 나를 위해 작동하지 않습니다

remoteViews.setInt(R.id.nmcButton, "setBackgroundColor", color); 
+0

setBackgroundColor 후 스타일을 잃는 문제를 해결하지 않았기 때문에 downvoted했습니다. –

+0

@BrenoSalgado 그럼 왜 downvote? 이것은 당신을위한 대답이 아닐지 모르지만 그것은 확실히 완벽하게 작동합니다.위의 답변도 해당 문제를 해결하지 못합니까? 이 방법을 사용한 후에도 스타일을 잃어 버렸다는 의견을 남길 수도 있습니다. –

+0

개인적인 내용은 없지만 문제를 제대로 해결하지 못했다고 생각합니다. Java/Android 응답의 품질은 너무 낮기 때문에 다소 낮다고 생각합니다. 루비 답변 (예를 들어)에서 나는 독자에게 문제가 무엇인지 설명하고, 솔루션을 제안하고, OP에서 작성된 각 질문을 처리하고, 링크를 제공하는 등의 답변을하는 데 익숙했다. 편지 하나만 대답하고 나머지는 무시하는 3 가지를 물어보십시오.), SO는 포럼이 아닙니다. (다시 말하지만, 나는 당신을 불쾌하게 할 뜻이 아니라 생각합니다. 참된) –

0

를, 그래서 해결 방법을 함께했다 :

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <ImageView 
     android:id="@+id/iv_widget_background" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:scaleType="fitXY" /> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@android:color/transparent" 
     android:orientation="vertical" 
     android:padding="@dimen/widget_listview_padding"> 

     <ListView 
      android:id="@+id/lv_widget" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:divider="@null" 
      android:dividerHeight="0dp" /> 
    </LinearLayout> 

</FrameLayout> 

가 그럼 난 이렇게 R.drawable에 드로어 블을 정의 :

이미지 뷰 내 배경을 그릴 수있는 곳

먼저 나는 FrameLayout이 될 내 레이아웃을 정의

red.xml : 나는 다음과 같은 않는의 AppWidgetProvider 내의 onUpdate() 함수에서 다음

 Intent intent = new Intent(context, WidgetProvider.class); 
     intent.setAction("android.appwidget.action.APPWIDGET_UPDATE"); 
     intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); 
     context.sendBroadcast(intent); 

: 사용자가 SharedPrefs를 통해 배경을 변경

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <solid android:color="#F44336" /> 
</shape> 

나는 다음을 수행해야 :

@Override 
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWdgetIds) { 
    try { 
     RemoteViews remoteViews; 
     for (int appWdgetId : appWdgetIds) { 
      remoteViews = updateWidgetListView(context, appWdgetId); 
      appWidgetManager.updateAppWidget(appWdgetId, remoteViews); 
     } 
     super.onUpdate(context, appWidgetManager, appWdgetIds); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

private RemoteViews updateWidgetListView(Context context, int appWidgetId) { 
    //which layout to show on widget 
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout); 
    Intent svcIntent = new Intent(context, WidgetService.class); 
    svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);  svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME))); 
    remoteViews.setRemoteAdapter(appWidgetId, R.id.lv_widget, svcIntent); 

    setBackground(context, remoteViews); 

    return remoteViews; 
} 

private void setBackground(Context context, RemoteViews remoteViews) { 
    String background = Utils.getStringValue(context, R.string.pref_widget_backgroundcolor_key, 
      R.string.pref_widget_backgroundcolor_default); 

    if (!TextUtils.isEmpty(background)) { 
     int identifier = context.getResources().getIdentifier(
       background, "drawable", context.getPackageName()); 
     remoteViews.setImageViewResource(R.id.iv_widget_background, identifier); 
    } 
} 

결과 :

enter image description here

관련 문제