我是Android新手。我被困住了,需要帮助。
我有一个列表作为我的Activity
。 OnItemLongClickListener
对于List的任何元素,我正在显示带有自定义列表(红色,绿色,蓝色)的对话框。在选择任何项目(红色,绿色,蓝色)时,我需要更改列表(主要活动)所选项目(事件引发对话框)的背景颜色。
弹出对话框,但我被困在如何获取所选项目(Dialog)。以下是我的代码。
public class SimpleList extends ListActivity
{
String[] contactNames = {"Name 1", "Name 2", "Name 3", "Name 4", "Name 5", "Name 6"};
ArrayAdapter<String> contactAdpater;
String itemSelected;
String choosenColor;
private final Context context = this;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ArrayList<String> myContactList = new ArrayList<String>(Arrays.asList(contactNames));
OnItemLongClickListener itemChangeColorListener = new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View arg1, int position, long arg3) {
itemSelected = parent.getItemAtPosition(position).toString();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
final String[] colorNames = {"Red","Green","Blue"};
builder.setTitle("Pick a Colour!")
.setItems(colorNames, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
choosenColor = colorNames[which];
//Toast.makeText(getApplicationContext(), colorNames[which], Toast.LENGTH_SHORT).show(); <<-- its working fine here
//I am not able to access parent here... I want to perform,
**//parent[position].setBackgroundColor(Color.RED); in case Red is selected from Dialog**
}
});
builder.show();
return false;
}
};
contactAdpater = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
myContactList);
setListAdapter(contactAdpater);
getListView().setOnItemLongClickListener(itemChangeColorListener);
}
}
答案 0 :(得分:0)
是的,你遇到了问题
您必须使用视图的 setBackgroundColor(int color); 来更改颜色,如果第一个ListView的选定项目具有从Dialog选择的颜色。
所以在onClick中你必须使用:
choosenColor = colorNames[which];
if(choosenColor.equals("Red"))
{
view.setBackgroundColor(Color.RED);
}
else if(choosenColor.equals("Blue"))
{
view.setBackgroundColor(Color.BLUE);
}
else if(choosenColor.equals("Green"))
{
view.setBackgroundColor(Color.GREEN);
}