Добрый день. Прошу помощи, так как перечитал много инфы, а ответа не нашел. И просьба не пинать сильно, так как я только начинающий )))
Вот такая задача: получить с удаленного сервиса json-данные, поместить данные в layout. Таких данных может быть много, следовательно layout`ы надо создавать динамически.
Сначала сделал так: по циклу разобрал json-массив. и в цикле начал создавать динамически разметку с layoutами и textviewшками. куда помещал информацию из массива. Все бы ни чего, правда код получился громоздкий ужасно. И не понял как написать обработчик onclick, что бы при нажатии на основной layout открыть новую активность и передать туда данные из этого layout`а.
Почитал по разным источникам и переделал по другому. Создал дополнительный файл разметки:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:background="@drawable/main_background"
android:orientation="vertical">
<LinearLayout
android:id="@+id/layout_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/white"
android:onClick="onLayoutClick"
android:orientation="vertical">
<LinearLayout
android:id="@+id/layout_data"
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal"
android:paddingEnd="5dp"
android:paddingStart="10dp"
android:paddingTop="5dp"
tools:ignore="RtlSymmetry">
<TextView
android:id="@+id/separator"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:layout_weight="1.9"
android:background="@drawable/separator"
android:gravity="center_vertical|center_horizontal" />
<LinearLayout
android:id="@+id/type_customer_address"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="0.5"
android:orientation="vertical">
<TextView
android:id="@+id/type"
android:layout_width="match_parent"
android:layout_height="20dp"
android:paddingStart="10dp"
android:textColor="@color/material_drawer_primary_text" />
<TextView
android:id="@+id/customer"
android:layout_width="match_parent"
android:layout_height="20dp"
android:paddingStart="10dp"
android:textColor="@color/material_drawer_secondary_text"
android:textSize="12sp" />
<TextView
android:id="@+id/address"
android:layout_width="match_parent"
android:layout_height="20dp"
android:paddingStart="10dp"
android:textColor="@color/material_drawer_secondary_text"
android:textSize="12sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/numer_date"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1.5"
android:orientation="vertical">
<TextView
android:id="@+id/numer"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#00aa00"
android:gravity="center_vertical|center_horizontal"
android:textSize="8sp"
tools:ignore="SmallSp" />
<TextView
android:id="@+id/date"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#00aa00"
android:gravity="center_vertical|center_horizontal"
android:textSize="8sp"
tools:ignore="SmallSp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/info_badges"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:orientation="horizontal"
android:paddingEnd="5dp"
tools:ignore="RtlSymmetry">
<TextView
android:id="@+id/info"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_weight="0.45"
android:textColor="#000000"
android:textSize="14sp" />
<LinearLayout
android:id="@+id/badges"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
android:layout_weight="1.55"
android:orientation="vertical">
<ImageView
android:id="@+id/badges1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="@string/map_task"
app:srcCompat="@android:drawable/ic_menu_mapmode" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/dropShadow" />
А в цикле через адаптер обрабатываю данные и вывожу в основной активности:
String url = "https://site.ru/task_user.php";
String json = "{\"user_id\":\""+mSettings.getString(APP_PREFERENCES_ID, "")+"\"}";
HttpPostGetActivity handler = new HttpPostGetActivity();
String result = "";
try {
result = handler.execute(url, json).get();
} catch (Exception e) {
e.printStackTrace();
}
ListView listViewAd = findViewById(R.id.LayoutTextView);
// Упаковываем данные
ArrayList<HashMap<String, Object>> data = new ArrayList<>();
HashMap<String, Object> map;
String[] resultParts = result.split("::");
for (String resultPart : resultParts) {
try {
JSONObject dataJsonObj = new JSONObject(resultPart);
JSONObject taskData = dataJsonObj.getJSONObject("Data");
taskId = taskData.getString("id");
JSONObject taskDateObj = taskData.getJSONObject("date");
taskDate = taskDateObj.getString("todo");
JSONObject taskType = taskData.getJSONObject("type");
nameType = taskType.getString("name");
JSONObject taskCustomer = taskData.getJSONObject("customer");
taskCustomerId = taskCustomer.getString("id");
taskCustomerFullName = taskCustomer.getString("fullName");
JSONObject taskAddressObj = taskData.getJSONObject("address");
taskAddressText = taskAddressObj.getString("text");
taskAddressCity = taskAddressObj.getString("cityId");
taskDescription = taskData.getString("description");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
resultPart,
Toast.LENGTH_SHORT).show();
}
map = new HashMap<>();
map.put("type", nameType);
map.put("customer", taskCustomerFullName);
map.put("address", taskAddressText);
map.put("numer", taskId);
map.put("date", taskDate);
map.put("info", taskDescription);
data.add(map);
}
// Массив имен атрибутов, из которых будут читаться данные
String[] from = {
"type",
"customer",
"address",
"numer",
"date",
"info"
};
// Массив идентификаторов компонентов, в которые будем вставлять данные
int[] to = {
R.id.type,
R.id.customer,
R.id.address,
R.id.numer,
R.id.date,
R.id.info
};
// создаем адаптер
SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.layout_block,
from, to);
// Устанавливаем адаптер для списка
listViewAd.setAdapter(adapter);
Подскажите пожалуйста, как правильно прописать обработчик onclick. То есть получается, что динамически создаются несколько layout. Если в xml-разметке прописать onclick, то он срабатывает одинаково. На какой бы лайоут не нажми. Как определить по какому именно лайоуту произведено нажатие и забрать данные из этого лайоута для передачи в другую активность.