![](/img/trans.png)
[英]How do I set the default state of a checkbox in ListView [Android]
[英]How do I set my checkbox checked by default after a certain action is performed in Android Studio?
每個人。 請幫助找到解決此問題的方法。 我將非常感激,我有一個帶有復選框列表的活動,一個復選框,單擊它后,將調用下一個操作。 執行,並完成,之后。 動作完成,應用程序返回到帶有復選框列表的動作,現在我希望默認選中使用的復選框並且無法再次單擊。 請幫忙!
這是我嘗試做但未成功的操作,當我返回操作時復選框未選中:
P2106.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Intent move = new Intent(GeneralRoute.this, ScanTest.class);
startActivity(move);
P2106.setChecked(true);
}
}
});
你的 model class
public class YourModel {
private boolean someBoolean;
private String someString;
private int someInt;
public boolean isSomeBoolean() {
return someBoolean;
}
public void setSomeBoolean(boolean someBoolean) {
this.someBoolean = someBoolean;
}
public String getSomeString() {
return someString;
}
public void setSomeString(String someString) {
this.someString = someString;
}
public int getSomeInt() {
return someInt;
}
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
你的活動
public class MainActivity extends AppCompatActivity {
private static ArrayList<YourModel> modelList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Add Your Model Or Data To ArrayList
modelList.add(new YourModel());
modelList.add(new YourModel());
ListView listView = findViewById(R.id.youtListView);
YourAdapter yourAdapter = new YourAdapter(this, R.id.youtLayoutListItem, modelList);
listView.setAdapter(yourAdapter);
}
}
和你的適配器
public class YourAdapter extends ArrayAdapter<YourModel> {
private ArrayList<YourModel> modelList;
public YourAdapter(@NonNull Context context, int resource, @NonNull List<YourModel> objects) {
super(context, resource, objects);
this.modelList = (ArrayList<YourModel>) objects;
}
@Override
public int getCount() {
return modelList.size();
}
@Nullable
@Override
public YourModel getItem(int position) {
return modelList.get(position);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
...
}
YourModel model = modelList.get(position);
P2106.setChecked(model.isSomeBoolean());
P2106.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Intent move = new Intent(GeneralRoute.this, ScanTest.class);
startActivity(move);
P2106.setChecked(true);
model.setSomeBoolean(true);
modelList.set(modelList.indexOf(model), model);
notifyDataSetChanged();
}
}
});
return convertView;
}
}
不要忘記用您的數據替換
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.