以下android代码会创建一个带有实心圆圈背景的TextView
。单击它时,会在其周围创建一个圆圈。如果再次单击,则圆圈消失。这在API 19中工作正常,但在API 8或10中没有。在那些较旧的API中,单击时不会绘制圆形边界。什么事在这里?
activity_main.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:background="#ffffff" >
<TextView
android:id="@+id/col1"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/circle_notapped"
android:layout_gravity="center"
android:layout_marginTop="50dp"/>
</LinearLayout>
MainActivity.java
package com.kitr.sview;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private int select1;
private TextView col1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
col1 = (TextView) findViewById(R.id.col1);
col1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(select1==0)
{
select1=1;
selectIt(v);
}
else
{
select1=0;
deselectIt(v);
}
}
});
initializeActivity();
}
private void initializeActivity()
{
LayerDrawable bgDrawable = (LayerDrawable)col1.getBackground();
GradientDrawable shape = (GradientDrawable) bgDrawable.findDrawableByLayerId(R.id.pat3);
shape.setColor(0xFFF04646);
select1=0;
}
private void selectIt(View v)
{
if(v.getId()==col1.getId())
{
LayerDrawable bgDrawable = (LayerDrawable)col1.getBackground();
GradientDrawable shape = (GradientDrawable) bgDrawable.findDrawableByLayerId(R.id.pat1);
shape.setColor(0xFFF04646);
}
}
private void deselectIt(View v)
{
if(v.getId()==col1.getId())
{
LayerDrawable bgDrawable = (LayerDrawable)col1.getBackground();
GradientDrawable shape = (GradientDrawable) bgDrawable.findDrawableByLayerId(R.id.pat1);
shape.setColor(Color.WHITE);
}
}
}
circle_notapped.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/pat1" android:top="0dp" android:left="0dp" android:right="0dp" android:bottom="0dp">
<shape android:shape="oval">
<solid android:color="#FFFFFFFF" />
</shape>
</item>
<item android:id="@+id/pat2" android:top="3dp" android:left="3dp" android:right="3dp" android:bottom="3dp">
<shape android:shape="oval">
<solid android:color="#FFFFFFFF" />
</shape>
</item>
<item android:id="@+id/pat3" android:top="6dp" android:left="6dp" android:right="6dp" android:bottom="6dp">
<shape android:shape="oval">
<solid android:color="#FF27AE60" />
</shape>
</item>
</layer-list>
答案 0 :(得分:0)
必须在较旧的API中使用View.Invalidate()
。这可能是一个黑客,但这很好。