Добрый день!
Хотелось бы создать список цветов с помощью массива нужных расцветок. Т.е. что-то вроде цветовой палитры.
Можно конечно вставить просто большую картику в Activity, но хотелось бы сделать именно список (ListView) программным путём.
Возможно ли такое? Если да, то как?
Какой тип массива нужен и где создать сам массив: в colors.xml, strings.xml или же в arrays.xml?
Нужно ли создавать свой адаптор или лучше использовать из тех, что уже существуют?
(Примеров списков строковых ресурсов очень много, но мне нужно только фоны менять каждого элемента в списке. )
ListActivity разноцветный список без текста ("палитра")
Re: ListActivity разноцветный список без текста ("палитра")
Надеюсь, что постановка вопроса ясна. Буду очень благодарна, если хоть кто-нибудь направит в нужное русло.
Re: ListActivity разноцветный список без текста ("палитра")
Один добрый человек помог мне.
Делюсь с решением задачи. Возможно, что у кого-нибудь могут тоже появиться похожие вопросы.
Итак:
1. Создаётся два xml-файла, один для элемента в списке, а другой - для всего списка.
"item.xml" - тут главным можно считать id y TextView:
[syntax=xml]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_margin="5dp"
android:gravity="center_horizontal"
android:text="@string/leer_text" />
</LinearLayout>[/syntax]
"farbpalette_layout.xml" в котором стоят ListView и TextView
[syntax=xml]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:orientation="vertical" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="332dp" >
</ListView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/leer_text" />
</LinearLayout>[/syntax]
2. Создаётся класс для Activity, например, "FarbenActivity.java"
[syntax=java]public class FarbenActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Находим Layout, в котором будет стоять сесь список
setContentView(R.layout.farbpalette_layout);
// Создаём список цветов
ArrayList<Integer> colors1 = new ArrayList<Integer>();
colors1.add(getResources().getColor(R.color.butter_yellow));
colors1.add(getResources().getColor(R.color.gray));
colors1.add(getResources().getColor(R.color.royal_blue));
// и другие цвета..
// Создаём адаптор, который принимает наш ArrayList
FarbenAdapter adapter = new FarbenAdapter(this, colors1);
// ListView в который вписываем с помощью адаптора наш ArrayList
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}}
[/syntax]
3. Создаётся адаптор, например, "FarbenAdapter.java":
[syntax=java]public class FarbenAdapter extends BaseAdapter {
private final Context context;
ArrayList<Integer> colorsarray = new ArrayList<Integer>();
public FarbenAdapter(Context context, ArrayList<Integer> colors) {
this.context = context;
colorsarray = colors;
}
@Override
public int getCount() {
return colorsarray.size();
}
@Override
public Object getItem(int position) {
return colorsarray.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// получим layout item, чтобы с ним дальше работать
View view = View.inflate(context, R.layout.item, null);
// дальше с него получим TextView
TextView colorText = (TextView) view.findViewById(R.id.text);
//дальше зададим этому TextView текст - это код цвета
//position у нас аргумент, показывающий позицию в листе..
colorText.setText(String.valueOf(getItem(position)));
// .. и задаем фон
colorText.setBackgroundColor((Integer)getItem(position));
return view;
}
}[/syntax]
Таким образом, получаем разноцветный список.
Успехов всем!
Делюсь с решением задачи. Возможно, что у кого-нибудь могут тоже появиться похожие вопросы.
Итак:
1. Создаётся два xml-файла, один для элемента в списке, а другой - для всего списка.
"item.xml" - тут главным можно считать id y TextView:
[syntax=xml]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_margin="5dp"
android:gravity="center_horizontal"
android:text="@string/leer_text" />
</LinearLayout>[/syntax]
"farbpalette_layout.xml" в котором стоят ListView и TextView
[syntax=xml]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:orientation="vertical" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="332dp" >
</ListView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/leer_text" />
</LinearLayout>[/syntax]
2. Создаётся класс для Activity, например, "FarbenActivity.java"
[syntax=java]public class FarbenActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Находим Layout, в котором будет стоять сесь список
setContentView(R.layout.farbpalette_layout);
// Создаём список цветов
ArrayList<Integer> colors1 = new ArrayList<Integer>();
colors1.add(getResources().getColor(R.color.butter_yellow));
colors1.add(getResources().getColor(R.color.gray));
colors1.add(getResources().getColor(R.color.royal_blue));
// и другие цвета..
// Создаём адаптор, который принимает наш ArrayList
FarbenAdapter adapter = new FarbenAdapter(this, colors1);
// ListView в который вписываем с помощью адаптора наш ArrayList
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}}
[/syntax]
3. Создаётся адаптор, например, "FarbenAdapter.java":
[syntax=java]public class FarbenAdapter extends BaseAdapter {
private final Context context;
ArrayList<Integer> colorsarray = new ArrayList<Integer>();
public FarbenAdapter(Context context, ArrayList<Integer> colors) {
this.context = context;
colorsarray = colors;
}
@Override
public int getCount() {
return colorsarray.size();
}
@Override
public Object getItem(int position) {
return colorsarray.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// получим layout item, чтобы с ним дальше работать
View view = View.inflate(context, R.layout.item, null);
// дальше с него получим TextView
TextView colorText = (TextView) view.findViewById(R.id.text);
//дальше зададим этому TextView текст - это код цвета
//position у нас аргумент, показывающий позицию в листе..
colorText.setText(String.valueOf(getItem(position)));
// .. и задаем фон
colorText.setBackgroundColor((Integer)getItem(position));
return view;
}
}[/syntax]
Таким образом, получаем разноцветный список.
Успехов всем!