我用自己的双手创建了一个自定义视图。我想添加一个微调器来选择不同的颜色,但出于某种原因,当我点击微调器时,它没有显示任何选项。我创建了一个4种颜色的数组。任何帮助,将不胜感激。这是我的代码和输出。
TouchDemo.java
public class TouchDemo extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner spinner;
//Custom View
SingleTouchEventView customView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touch_demo);
customView = new SingleTouchEventView(this.getBaseContext(),null);
ConstraintLayout l = (ConstraintLayout) findViewById(R.id.myLayout);
l.addView(customView);
spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter adapter= ArrayAdapter.createFromResource(this,R.array.colors,android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view;
Toast.makeText(this,"you have selected " + txt.getText(),Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
SingletouchEvent.java
public class SingleTouchEventView extends View {
private Paint p = new Paint();
private Path pt = new Path();
public SingleTouchEventView(Context context, AttributeSet attrs) {
/**
* these following codes are hardcoded
*/
super(context, attrs);
p.setAntiAlias(true);
p.setStrokeWidth(3);
p.setColor(Color.GREEN);
p.setStyle(Paint.Style.STROKE);
p.setStrokeJoin(Paint.Join.ROUND);
}
activity_touch_demo.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.makkhay.touchdemo.TouchDemo">
<Spinner
android:id="@+id/spinner1"
android:layout_width="0dp"
android:layout_height="wrap_content"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="16dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
app:layout_constraintHorizontal_bias="0.0" />
</android.support.constraint.ConstraintLayout>
的strings.xml
<resources>
<string name="app_name">TouchDemo</string>
<string-array name="colors">
<item>Purple</item>
<item>Red</item>
<item>Green</item>
<item>Yellow</item>
</string-array>
</resources>
这是我的输出: