gpt4 book ai didi

android - ListView 中自定义可检查元素的初始状态 "checked"

转载 作者:行者123 更新时间:2023-11-30 03:02:32 25 4
gpt4 key购买 nike

我正在尝试使用自定义“Checkable”元素构建 list 。我能够显示列表、选中复选框(它是一个 ImageView)并将每个复选框的状态保存在数据库中。

不幸的是,当我打开 list 时,我想用一些选中的复选框初始化 list ,但我做不到。它不起作用。


截图

这是我打开 list 时的屏幕:

android screen that display a checklist with every checkbox unchecked

图例:显示每个复选框都未选中的 list 的安卓屏幕

我使用方法 .setEnabled(true/false) 来直观地显示不同的状态(用于调试目的)。

基本上,当我作为用户勾选复选框时,它看起来像这样:

android screen with a checkbox checked

图例:选中复选框的安卓屏幕


层次结构

  • 来源
    • com.checkit.app(包)
      • CheckableLinearLayout.java
      • TasksActivity.java
      • TasksAdapter.java <=(我认为问题可以在这个文件的某处解决)
      • [...]
  • 资源
    • 可绘制
      • ic_hideable_item.xml
    • drawable-mdpi
      • btn_check_off.png
      • btn_check_on.png
      • [...]
    • 布局
      • activity_tasks.xml
      • task_items.xml
      • [...]

代码

任务适配器.java

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
* @author tony
*
*/
public class TasksAdapter extends BaseAdapter {


/* ************************************* properties */

// list of items
private ArrayList<Task> mItemsList;

// context
private Context mContext;

// a single task
private Task taskItem = null;


/* ************************************* contructors */

/**
* @param context
* @param item
*/
public TasksAdapter(Context context, ArrayList<Task> pTasksItems) {
this.mContext = context;
this.mItemsList = pTasksItems;
}


/* ************************************* override methods */

@Override
public int getCount() {
return mItemsList.size();
}

@Override
public Task getItem(int position) {
return mItemsList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}


/**
* Display the view of the task of a checklist
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {

// if we access for the first time : we have to user LayoutInflater
if (convertView == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.task_items, null);
}

// get the font size (from the SharedPreferences)
String fontSizeSetting = MainActivity.getmFontSize();

// set the text on the tasks
//CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.task);
com.checkit.app.CheckableLinearLayout checkboxGlobal = (com.checkit.app.CheckableLinearLayout) convertView.findViewById(R.id.taskGlobalCheckbox);
ImageView checkboxImg = (ImageView) convertView.findViewById(R.id.taskImageCheckbox);
TextView checkboxTxt = (TextView) convertView.findViewById(R.id.task_text);

// get the Task
taskItem = (Task) mItemsList.get(position);

// is this task done ?
// .getIsTick values are 0 (false) or 1 (true)
if (taskItem.getIsTick() == 1) {
// the task is done, so tick the checkbox
Log.d("TEST", "TasksAdapter getView() is getIsTick");

// TODO I should do something here to tick the box. But what should I do ??
checkboxGlobal.setChecked(true); // I go to the method, but this do nothing ??
checkboxGlobal.setEnabled(true); // just to show that it's well working


// INFO : below are a lot of tries, but no one works properly
//StateListDrawable states = new StateListDrawable();
//Drawable drawable = convertView.getResources().getDrawable(R.drawable.ic_hideable_item);
//drawable.setState(new int[] {android.R.attr.state_checked});
//states.addState(new int[] {android.R.attr.state_checked}, drawable);
//states.setState(new int[] {android.R.attr.state_checked});
//checkboxImg.setImageDrawable(states);
//checkboxImg.setImageDrawable(drawable);

} else {
// the task is undone, so untick the checkbox
Log.d("TEST", "TasksAdapter getView() is not getIsTick");

checkboxGlobal.setChecked(false);
checkboxGlobal.setEnabled(false);

}

// set the text on the TextView
checkboxTxt.setText(taskItem.getName());

// change the font size
checkboxTxt.setTextSize(Float.parseFloat(fontSizeSetting));

// return the view
return convertView;
}

}

CheckableLinearLayout.java

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Checkable;
import android.widget.LinearLayout;

/**
* File based on the official example (cf. http://developer.android.com/samples/CustomChoiceList/index.html )
*
* This is a simple wrapper for {@link android.widget.LinearLayout} that implements the {@link android.widget.Checkable}
* interface by keeping an internal 'checked' state flag.
* <p>
* This can be used as the root view for a custom list item layout for
* {@link android.widget.AbsListView} elements with a
* {@link android.widget.AbsListView#setChoiceMode(int) choiceMode} set.
*/
public class CheckableLinearLayout extends LinearLayout implements Checkable {


/* ************************************* properties */

// android state for "checked"
private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};

// default state : FALSE = every checkbox are untick
private boolean mChecked = false;


/* ************************************* contructors */

/**
* @param context
* @param attrs
*/
public CheckableLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}


/* ************************************* override methods */

@Override
public int[] onCreateDrawableState(int extraSpace) {
int[] drawableState = super.onCreateDrawableState(extraSpace + 1);

if (isChecked()) {
Log.d("TEST ", "CheckableLinearLayout.onCreateDrawableState("+extraSpace+") (isChecked TRUE)");
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}

return drawableState;
}


/* ************************************* aspects methods */

/**
* Is this checked ?
*/
public boolean isChecked() {
Log.d("TEST ", "CheckableLinearLayout.isChecked()");
return mChecked;
}


/**
* Set the item as checked (if it's not yet)
*/
@Override
public void setChecked(boolean b) {
Log.d("TEST ", "CheckableLinearLayout.setChecked()");

// close if it's still the same state
if (b == mChecked) {
return;
}

Log.d("TEST ", "CheckableLinearLayout.setChecked() inside");

// modify the state
mChecked = b;
// refresh the drawable state
refreshDrawableState();
}


/**
* Toggle current state
*/
public void toggle() {
Log.d("TEST ", "CheckableLinearLayout.toggle()");
setChecked(!mChecked);
}

}

ic_hideable_item.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="@drawable/btn_check_on"
/>
<item
android:state_checked="false"
android:drawable="@drawable/btn_check_off"
/>
</selector>

activity_tasks.xml

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ListView
android:id="@+id/listTasks"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="multipleChoice"
/>
</LinearLayout>

task_items.xml

<?xml version="1.0" encoding="utf-8"?>
<com.checkit.app.CheckableLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/taskGlobalCheckbox"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:minHeight="?android:listPreferredItemHeight"
android:orientation="horizontal"
>

<ImageView
android:id="@+id/taskImageCheckbox"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:duplicateParentState="true"
android:src="@drawable/ic_hideable_item"
android:contentDescription="@string/img_alt_checkbox"
/>

<TextView
android:id="@+id/task_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:duplicateParentState="true"
android:paddingTop="10dip"
android:paddingRight="10dip"
android:paddingBottom="10dip"
/>

</com.checkit.app.CheckableLinearLayout>

更多

下面是我想说的一些话:

  • checkboxGlobal.setEnabled(true); 工作完美,正如我们在屏幕截图(灰色标题)中看到的那样。但是checkboxGlobal.setChecked(true);好像没有效果(?)
  • 有一次,我尝试了 Drawable drawable = convertView.getResources().getDrawable(R.drawable.ic_hideable_item);,然后是 checkboxImg.setImageDrawable(states);。使用选中的复选框初始化复选框非常有效,但无法取消选中该框。

编辑 2014-03-12:我的代码基于“Android 开发者”网站的官方代码示例(参见项目“CustomChoiceList”,可在此处获取:http://developer.android.com/samples/CustomChoiceList/index.html)。

编辑 2014-03-13 : 删除不必要的代码,以提高可读性

在此先感谢您的帮助。随时询问您是否需要更多代码。真挚地,托尼

最佳答案

我找到了答案。它似乎不是很有效,但它确实有效。我的答案是基于DroidBender的代码。

对于那些可能感兴趣的人,这里是 TasksAdapter.java 中 .getView() 方法的代码:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

// if we access for the first time : we have to user LayoutInflater
if (convertView == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.task_items, null);
}

// get the font size (from the SharedPreferences)
String fontSizeSetting = MainActivity.getmFontSize();

// set the text on the tasks
checkboxGlobal = (com.checkit.app.CheckableLinearLayout) convertView.findViewById(R.id.taskGlobalCheckbox);
checkboxImg = (ImageView) convertView.findViewById(R.id.taskImageCheckbox);
checkboxTxt = (TextView) convertView.findViewById(R.id.task_text);

// get the Task ( "final" <= very important)
final Task taskItemFinal = (Task) mItemsList.get(position);

// is the task done ?
boolean isTick = (taskItemFinal.getIsTick() == 1 ? true : false );

// init
Drawable drawable = null;

// is this task done ?
if (isTick) {
// the task is done, so tick the checkbox
drawable = convertView.getResources().getDrawable(R.drawable.btn_check_on);
} else {
// the task is undone, so untick the checkbox
drawable = convertView.getResources().getDrawable(R.drawable.btn_check_off);
}
// set the initial drawable
checkboxImg.setImageDrawable(drawable);

// click event on the checkbox
checkboxGlobal.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

// is the checkbox ticked ?
boolean isTick = (taskItemFinal.getIsTick() == 1 ? true : false );

Drawable drawable = null;

// set a different drawable depending to the state
if (isTick) {
drawable = v.getResources().getDrawable(R.drawable.btn_check_off);
} else {
drawable = v.getResources().getDrawable(R.drawable.btn_check_on);
}

// set the drawable to the element
checkboxImg = (ImageView) v.findViewById(R.id.taskImageCheckbox);
checkboxImg.setImageDrawable(drawable);

// toggle
taskItemFinal.toggle();

// Open the connection
TaskDAO taskDao = new TaskDAO(v.getContext());
taskDao.open();

// update the data
taskDao.update(taskItemFinal);

// set to false
return false;
}
});

// set the text on the TextView
checkboxTxt.setText(taskItemFinal.getName());

// change the font size
checkboxTxt.setTextSize(Float.parseFloat(fontSizeSetting));

// return the view
return convertView;
}

技巧包括使用名为 taskItemFinal 的最终变量,并在 .taskItemFinal() 方法中使用它。然后我自己改变drawable。在这种情况下,您必须删除 TasksActivity.java 文件中的 .setOnItemClickListener(就像我之前为保存状态所做的那样)。

希望对您有所帮助。

关于android - ListView 中自定义可检查元素的初始状态 "checked",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22325487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com