我试图添加一个字符串(to do activity)和一个布尔值(toggle是紧急的,untoggled不是紧急的)。为此,我创建了一个名为ToDos的类,并在该类中包含String和Boolean。
然而,我得到的错误是字符串应该是ToDos(类的名称),我不知道如何避免这种情况。
主要活动。Java语言
package com.example.androidlabs;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button button1;
EditText editText;
ListView listView;
ListAdapter adapter;
Switch switch1;
ArrayList<ToDos> taskList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskList.add(new ToDos("Mow the lawn",false));
taskList.add(new ToDos("Do groceries", false));
taskList.add(new ToDos("Change oil", true));
//variables
button1 = (Button) findViewById(R.id.button1);
editText = (EditText) findViewById(R.id.edittext1);
switch1 = findViewById(R.id.switch1);
listView = (ListView) findViewById(R.id.TheListView);
listView.setAdapter(adapter = new ListAdapter());
//onClick
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v){
taskList.add(new ToDos(taskList.add(editText.getText().toString()), switch1.isChecked()));
editText.setText("");
adapter.notifyDataSetChanged();
}
});
}
//adapter
class ListAdapter extends BaseAdapter{
@Override
public int getCount() {
return taskList.size();
}
@Override
public ToDos getItem(int position) {
return taskList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View old, ViewGroup parent) {
View newView =old;
LayoutInflater inflater = getLayoutInflater();
if(newView==null){
newView = inflater.inflate(R.layout.row_layout,parent,false);
}
TextView textview= newView.findViewById(R.id.textgoeshere);
textview.setText(getItem(position).text);
if(getItem(position).IsUrgent){
textview.setBackgroundColor(Color.RED);
}
return newView;
}
}
public class ToDos {
public String text;
public Boolean IsUrgent;
public ToDos(String text, Boolean IsUrgent) {
this.text = text;
this.IsUrgent = IsUrgent;
}
}
}
问题具体在于这一行:
taskList.add(new ToDos(taskList.add(editText.getText().toString()),switch1.isChecked()));
然而,我已经尝试了我能想到的一切,我被难住了。有人有什么想法吗?