使用android中的颜色选择器更改textview的文本颜色和背景颜色

时间:2013-06-10 11:34:19

标签: android android-layout textview color-picker

如何使用android中的颜色选择器更改TextView的文本颜色和背景颜色。 添加具有更改文本颜色的功能的注释和从颜色选择器中选择颜色的背景。

Note

4 个答案:

答案 0 :(得分:9)

  • 下载此项目导入它。Color-picker

  • 右键点击项目---> property ---> android --->添加点击并添加下载项目。

  • 创建新项目
  • 布局 注意:使用下载的项目res文件夹中的颜色选择器图像--->可绘制

     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" >
    
         <EditText
            android:id="@+id/txNote"
            android:layout_width="200dip"
            android:layout_height="200dip"
            android:layout_centerInParent="true"
            android:text="@string/hello_world" />
    
         <ImageView
             android:id="@+id/rightColorPicker"
             android:layout_width="@dimen/ambilwarna_hueWidth"
             android:layout_height="@dimen/ambilwarna_hsvHeight"
             android:layout_alignParentRight="true"
             android:layout_alignTop="@+id/txNote"
             android:scaleType="fitXY"
             android:src="@drawable/ambilwarna_hue" />
    
         <ImageView
             android:id="@+id/leftColorPicker"
             android:layout_width="@dimen/ambilwarna_hueWidth"
             android:layout_height="@dimen/ambilwarna_hsvHeight"
             android:layout_alignParentLeft="true"
             android:layout_alignTop="@+id/txNote"
             android:scaleType="fitXY"
             android:src="@drawable/ambilwarna_hue" />
    
    </RelativeLayout>
    
    • 活动

      public class MainActivity extends Activity implements OnTouchListener {
      
      TextView txtNote;
      ImageView rightColorPicker,leftColorPicker;
      private int mAppWidgetId = 0 ;
      public static boolean flag;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          txtNote=(TextView)findViewById(R.id.txNote);
          rightColorPicker=(ImageView)findViewById(R.id.rightColorPicker);
          leftColorPicker=(ImageView)findViewById(R.id.leftColorPicker);
          rightColorPicker.setOnTouchListener(this);
          leftColorPicker.setOnTouchListener(this);
          Intent intent = getIntent();
          Bundle extras = intent.getExtras();
          if (extras != null) {
      
              mAppWidgetId = extras.getInt(
                      AppWidgetManager.EXTRA_APPWIDGET_ID, 
                      AppWidgetManager.INVALID_APPWIDGET_ID);
      
          }
      
      }
      
      @Override
      public boolean onTouch(View v, MotionEvent event) {
          switch (v.getId()) {
          case R.id.rightColorPicker:
              colorPicker();
              flag=true;
              break;
          case R.id.leftColorPicker:
              colorPicker();
              flag=false;
              break;
          default:
              break;
          }
      
          return false;
      }
      
      public void colorPicker() {
      
      //      initialColor is the initially-selected color to be shown in the rectangle on the left of the arrow.
      //      for example, 0xff000000 is black, 0xff0000ff is blue. Please be aware of the initial 0xff which is the alpha.
      ColorPickerDialog dialog = new ColorPickerDialog(this, 0xff0000ff, new OnAmbilWarnaListener() {
      
          // Executes, when user click Cancel button
          @Override
          public void onCancel(ColorPickerDialog dialog){
          }
      
          // Executes, when user click OK button
          @Override
          public void onOk(ColorPickerDialog dialog, int color) {
              // Create an Intent to launch WidgetConfigurationActivity screen
              Intent intent = new Intent(getBaseContext(), MainActivity.class);
      
              intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
      
              // This is needed to make this intent different from its previous intents 
              intent.setData(Uri.parse("tel:/"+ (int)System.currentTimeMillis()));
      
              // Creating a pending intent, which will be invoked when the user
              // clicks on the widget
              PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, 
                      intent, PendingIntent.FLAG_UPDATE_CURRENT);                     
      
              // Getting an instance of WidgetManager
              AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext());
      
              if (flag) {
                   txtNote.setBackgroundColor(color);
      
              } else {
                  txtNote.setTextColor(color);
              }
      
      // // Instantiating the class RemoteViews with widget_layout
            RemoteViews views = new 
            RemoteViews(getBaseContext().getPackageName(), R.layout.activity_main);
      //  
      // // Setting the background color of the widget
            views.setInt(R.id.txNote, "setBackgroundColor", color);                        
      //                          
      // //  Attach an on-click listener to the clock
           views.setOnClickPendingIntent(R.id.txNote,pendingIntent);
      
              // Tell the AppWidgetManager to perform an update on the app widget
              appWidgetManager.updateAppWidget(mAppWidgetId, views);                        
      
              // Return RESULT_OK from this activity
              Intent resultValue = new Intent();
              resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
              setResult(RESULT_OK, resultValue);
              //finish();
          }
      });
      dialog.show();
      }
      }
      

答案 1 :(得分:1)

您可以使用以下内容作为参考。它可能不完全像你的问题中发布的快照。您可以使用以下内容并根据您的要求进行修改。

单击按钮时,会弹出颜色选择器对话框。您可以选择颜色并单击中心圆。 textview文本颜色更改为选择的颜色。

public class MainActivity extends Activity  implements ColorPickerDialog.OnColorChangedListener  {

    Button b1;
    TextView tv;
    Paint mPaint;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPaint = new Paint();
        tv = (TextView) findViewById(R.id.tv);
        b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new ColorPickerDialog(MainActivity.this, MainActivity.this, mPaint.getColor()).show();
            }

        });
    }
    @Override
    public void colorChanged(int color) {
        // TODO Auto-generated method stub
        tv.setTextColor(color);
    }

}

拾色器

public class ColorPickerDialog extends Dialog {

    public interface OnColorChangedListener {
        void colorChanged(int color);
    }

    private OnColorChangedListener mListener;
    private int mInitialColor;

    private static class ColorPickerView extends View {
        private Paint mPaint;
        private Paint mCenterPaint;
        private final int[] mColors;
        private OnColorChangedListener mListener;

        ColorPickerView(Context c, OnColorChangedListener l, int color) {
            super(c);
            mListener = l;
            mColors = new int[] {
                0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
                0xFFFFFF00, 0xFFFF0000
            };
            Shader s = new SweepGradient(0, 0, mColors, null);

            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setShader(s);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(32);

            mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mCenterPaint.setColor(color);
            mCenterPaint.setStrokeWidth(5);
        }

        private boolean mTrackingCenter;
        private boolean mHighlightCenter;

        @Override
        protected void onDraw(Canvas canvas) {
            float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;

            canvas.translate(CENTER_X, CENTER_X);

            canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
            canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);

            if (mTrackingCenter) {
                int c = mCenterPaint.getColor();
                mCenterPaint.setStyle(Paint.Style.STROKE);

                if (mHighlightCenter) {
                    mCenterPaint.setAlpha(0xFF);
                } else {
                    mCenterPaint.setAlpha(0x80);
                }
                canvas.drawCircle(0, 0,
                                  CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
                                  mCenterPaint);

                mCenterPaint.setStyle(Paint.Style.FILL);
                mCenterPaint.setColor(c);
            }
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
        }

        private static final int CENTER_X = 100;
        private static final int CENTER_Y = 100;
        private static final int CENTER_RADIUS = 32;

        private int floatToByte(float x) {
            int n = java.lang.Math.round(x);
            return n;
        }
        private int pinToByte(int n) {
            if (n < 0) {
                n = 0;
            } else if (n > 255) {
                n = 255;
            }
            return n;
        }

        private int ave(int s, int d, float p) {
            return s + java.lang.Math.round(p * (d - s));
        }

        private int interpColor(int colors[], float unit) {
            if (unit <= 0) {
                return colors[0];
            }
            if (unit >= 1) {
                return colors[colors.length - 1];
            }

            float p = unit * (colors.length - 1);
            int i = (int)p;
            p -= i;

            // now p is just the fractional part [0...1) and i is the index
            int c0 = colors[i];
            int c1 = colors[i+1];
            int a = ave(Color.alpha(c0), Color.alpha(c1), p);
            int r = ave(Color.red(c0), Color.red(c1), p);
            int g = ave(Color.green(c0), Color.green(c1), p);
            int b = ave(Color.blue(c0), Color.blue(c1), p);

            return Color.argb(a, r, g, b);
        }

        private int rotateColor(int color, float rad) {
            float deg = rad * 180 / 3.1415927f;
            int r = Color.red(color);
            int g = Color.green(color);
            int b = Color.blue(color);

            ColorMatrix cm = new ColorMatrix();
            ColorMatrix tmp = new ColorMatrix();

            cm.setRGB2YUV();
            tmp.setRotate(0, deg);
            cm.postConcat(tmp);
            tmp.setYUV2RGB();
            cm.postConcat(tmp);

            final float[] a = cm.getArray();

            int ir = floatToByte(a[0] * r +  a[1] * g +  a[2] * b);
            int ig = floatToByte(a[5] * r +  a[6] * g +  a[7] * b);
            int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);

            return Color.argb(Color.alpha(color), pinToByte(ir),
                              pinToByte(ig), pinToByte(ib));
        }

        private static final float PI = 3.1415926f;

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX() - CENTER_X;
            float y = event.getY() - CENTER_Y;
            boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mTrackingCenter = inCenter;
                    if (inCenter) {
                        mHighlightCenter = true;
                        invalidate();
                        break;
                    }
                case MotionEvent.ACTION_MOVE:
                    if (mTrackingCenter) {
                        if (mHighlightCenter != inCenter) {
                            mHighlightCenter = inCenter;
                            invalidate();
                        }
                    } else {
                        float angle = (float)java.lang.Math.atan2(y, x);
                        // need to turn angle [-PI ... PI] into unit [0....1]
                        float unit = angle/(2*PI);
                        if (unit < 0) {
                            unit += 1;
                        }
                        mCenterPaint.setColor(interpColor(mColors, unit));
                        invalidate();
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (mTrackingCenter) {
                        if (inCenter) {
                            mListener.colorChanged(mCenterPaint.getColor());
                        }
                        mTrackingCenter = false;    // so we draw w/o halo
                        invalidate();
                    }
                    break;
            }
            return true;
        }
    }

    public ColorPickerDialog(Context context,
                             OnColorChangedListener listener,
                             int initialColor) {
        super(context);

        mListener = listener;
        mInitialColor = initialColor;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OnColorChangedListener l = new OnColorChangedListener() {
            public void colorChanged(int color) {
                mListener.colorChanged(color);
                dismiss();
            }
        };

        setContentView(new ColorPickerView(getContext(), l, mInitialColor));
        setTitle("Pick a Color");
    }
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv"
        android:layout_above="@+id/button1"
        android:layout_alignRight="@+id/button1"
        android:layout_marginBottom="180dp"
        android:text="@string/hello_world" />

</RelativeLayout>

enter image description here

您还可以使用https://code.google.com/p/android-color-picker/中的颜色选择器 活性

enter image description here

答案 2 :(得分:0)

正如在这个问题中回答的那样:Android Color Picker有一个颜色选择器的例子。使用它你可以改变颜色:

        Color colorPicket = Color.parse("color returned of color picket");
        TextView textView = (TextView) v;
        textView.setBackgroundColor(colorPicked); //if it returns in hex you can parse with COlor.par
        textView.setTextColor(colorPicked);

看看:Color.parseColor

答案 3 :(得分:0)

我不知道你是如何从拾取器中获取颜色的,所以我想你可以将它作为RGB颜色/十六进制的三元组。然后你必须使用方法setTextColor(int color)many possibilities

myTextView.setTextColor(Color.rgb(100,100,100)); //get color as a triplet RGB
myTextView.setTextColor(Color.parseColor("#FFFFFF")); //get color as hexadecimal String

要设置textView的背景,请使用方法setBackgroundColor(int color)(继承自View类):

myTextView.setBackgroundColor(Color.rgb(100,100,100)); //example