0

Создал RecyclerView c CardView. Все работает, данные устанавливаются через адаптер, но не могу прочитать текст с EditText при клике по кнопке. P.S.: почему то все свойства EditText через отладчик показываются как Null или -1. В чем может быть проблема?

MainActivity.java

package com.example.nik.greenery;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    BluetoothSocket clientSocket;
    ArrayList<String> nameDeviceList = new ArrayList<>();
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    EditText nameDevice;
    Button buttonApply;
   /* CircularProgressBar tempProgressBar = (CircularProgressBar)findViewById(R.id.progress_bar_temperature);
    CircularProgressBar humProgressBar = (CircularProgressBar)findViewById(R.id.progress_bar_humidyty);*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        RecyclerView rv = (RecyclerView)findViewById(R.id.rv);

        rv.setHasFixedSize(true);
        List<Object> sensorsDataList = new ArrayList<>();
        LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this);
        rv.setLayoutManager(llm);
        sensorsDataList.add(new SensorsData("67", "67", "NaN", "NaN"));
        sensorsDataList.add(new SensorsData("67", "67", "NaN", "NaN"));

        //sensorsDataList.add(new SensorsData("100", "100", "NaN", "NaN"));
        rv.setAdapter(new ComplexRecyclerViewAdapter(sensorsDataList));

        LayoutInflater inflater = this.getLayoutInflater();
        View view = inflater.inflate(R.layout.name_device, null);
        nameDevice = view.findViewById(R.id.editNameDevice);
        Log.d("Text", nameDevice.getText().toString());
        buttonApply = view.findViewById(R.id.buttonApply);

        startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);

        if (bluetoothAdapter == null) {
            new AlertDialog.Builder(this)
                    .setTitle("Not compatible")
                    .setMessage("Your phone does not support Bluetooth")
                    .setPositiveButton("Exit", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }
    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_sensor) {
            // Handle the camera action
        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_hand_mode) {

        } else if (id == R.id.nav_plots) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void apply_click(View view) {
        Log.d("HELLO", "HELLO");
        String name = nameDevice.getText().toString();
        Log.d("name", name);
    }
}

ComplexRecycleViewAdapter.java

package com.example.nik.greenery;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by Nik on 30.04.2018.
 */

public class ComplexRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>  {

    // The items to display in your RecyclerView
    private List<Object> items;

    private final int NAME_DEVICE = 0, HUM_AND_TEMP = 1;

    // Provide a suitable constructor (depends on the kind of dataset)
    public ComplexRecyclerViewAdapter(List<Object> items) {
        this.items = items;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        switch (viewType){
            case NAME_DEVICE:
                View v1 = inflater.inflate(R.layout.name_device, parent, false);
                viewHolder = new NameDeviceViewHolder(v1);
                break;
            case HUM_AND_TEMP:
                View v2 = inflater.inflate(R.layout.temperature_and_hum, parent,false);
                viewHolder = new TempHumViewHolder(v2);
                break;
            default:
                View v3 = inflater.inflate(R.layout.name_device, parent, false);
                viewHolder = new NameDeviceViewHolder(v3);
                break;
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        switch (holder.getItemViewType()){
            case NAME_DEVICE:
                NameDeviceViewHolder vh1 = (NameDeviceViewHolder) holder;
                configureViewHolderNameDevice(vh1, position);
                break;
            case HUM_AND_TEMP:
                TempHumViewHolder vh2 = (TempHumViewHolder) holder;
                configureViewHolderTempHum(vh2, position);
                break;
            default:
                break;
        }
    }

    private void configureViewHolderTempHum(TempHumViewHolder vh2, int position) {
        SensorsData sensorsData = (SensorsData)items.get(position);
        if (sensorsData != null){
            vh2.getHum().setText(sensorsData.getHumAir());
            vh2.getHumProgressBar().setProgress(Float.parseFloat(sensorsData.getHumAir()));
            vh2.getTemp().setText(sensorsData.getTemp());
            vh2.getTempProgressBar().setProgress(Float.parseFloat(sensorsData.getTemp()));
        }
    }

    private void configureViewHolderNameDevice(NameDeviceViewHolder vh1, int position) {

    }

    //Returns the view type of the item at position for the purposes of view recycling.
    @Override
    public int getItemViewType(int position) {
        Log.d("Position", String.valueOf(position));
        if (position == 0) {
            return NAME_DEVICE;
        } else if (position == 1) {
            return HUM_AND_TEMP;
        }
        return -1;
    }

    @Override
    public int getItemCount() {
        return this.items.size();
    }
}

NameDeviceViewHolder.java

package com.example.nik.greenery;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * Created by Nik on 30.04.2018.
 */


public class NameDeviceViewHolder extends RecyclerView.ViewHolder {

    public NameDeviceViewHolder(View itemView) {
        super(itemView);
    }
}

TempHumViewHolder.java

package com.example.nik.greenery;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.budiyev.android.circularprogressbar.CircularProgressBar;

/**
 * Created by Nik on 30.04.2018.
 */

public class TempHumViewHolder extends RecyclerView.ViewHolder {

    private CircularProgressBar tempProgressBar;
    private CircularProgressBar humProgressBar;
    private TextView nameAir;
    private TextView temp;
    private TextView hum;
    private TextView tempText;
    private TextView humText;

    public TempHumViewHolder(View itemView) {
        super(itemView);
        tempProgressBar = itemView.findViewById(R.id.progress_bar_temperature);
        humProgressBar = itemView.findViewById(R.id.progress_bar_humidyty);
        nameAir = itemView.findViewById(R.id.air);
        temp = itemView.findViewById(R.id.temp_text);
        hum = itemView.findViewById(R.id.hum_text);
        tempText = itemView.findViewById(R.id.temperature);
        humText = itemView.findViewById(R.id.humidity);
    }

    public CircularProgressBar getTempProgressBar(){
        return this.tempProgressBar;
    }

    public CircularProgressBar getHumProgressBar(){
        return this.humProgressBar;
    }

    public TextView getNameAir(){
        return this.nameAir;
    }

    public TextView getTemp(){
        return this.temp;
    }

    public TextView getHum(){
        return this.hum;
    }

    public TextView getTempText(){
        return this.tempText;
    }

    public TextView getHumText(){
        return this.humText;
    }

    public void setHumProgressBar(CircularProgressBar humProgressBar) {
        this.humProgressBar = humProgressBar;
    }

    public void setNameAir(TextView nameAir) {
        this.nameAir = nameAir;
    }

    public void setTempProgressBar(CircularProgressBar tempProgressBar) {
        this.tempProgressBar = tempProgressBar;
    }

    public void setHum(TextView hum) {
        this.hum = hum;
    }

    public void setTemp(TextView temp) {
        this.temp = temp;
    }

    public void setHumText(TextView humText) {
        this.humText = humText;
    }

    public void setTempText(TextView tempText) {
        this.tempText = tempText;
    }

}

temperature_and_hum.xml

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="12dp">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        style="@style/MyCardViewStyle"
        android:layout_width="329dp"
        android:layout_height="235dp"
        android:layout_gravity="center"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp">


        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <com.budiyev.android.circularprogressbar.CircularProgressBar
                android:id="@+id/progress_bar_temperature"
                android:layout_width="129dp"
                android:layout_height="127dp"
                android:layout_marginTop="40dp"
                app:animateProgress="true"
                app:backgroundStrokeColor="#ff3f51b5"
                app:backgroundStrokeWidth="2dp"
                app:drawBackgroundStroke="false"
                app:foregroundStrokeCap="butt"
                app:foregroundStrokeColor="#ffff4081"
                app:foregroundStrokeWidth="3dp"
                app:indeterminate="false"
                app:indeterminateMinimumAngle="45"
                app:indeterminateRotationAnimationDuration="1200"
                app:indeterminateSweepAnimationDuration="600"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:maximum="100"
                app:progress="50"
                app:progressAnimationDuration="100"
                app:startAngle="270"
                tools:ignore="MissingConstraints" />

            <TextView
                android:id="@+id/temp_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:gravity="center"
                android:text="@string/nan"
                android:textSize="24sp"
                app:layout_constraintBottom_toBottomOf="@+id/progress_bar_temperature"
                app:layout_constraintEnd_toEndOf="@+id/progress_bar_temperature"
                app:layout_constraintStart_toStartOf="@+id/progress_bar_temperature"
                app:layout_constraintTop_toTopOf="@+id/progress_bar_temperature"
                app:layout_constraintVertical_bias="0.506"
                tools:ignore="MissingConstraints" />


            <TextView
                android:id="@+id/temperature"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:text="@string/temperature"
                android:textSize="18sp"
                app:layout_constraintEnd_toEndOf="@+id/progress_bar_temperature"
                app:layout_constraintStart_toStartOf="@+id/progress_bar_temperature"
                app:layout_constraintTop_toBottomOf="@+id/progress_bar_temperature"
                tools:ignore="MissingConstraints" />

            <com.budiyev.android.circularprogressbar.CircularProgressBar
                android:id="@+id/progress_bar_humidyty"
                android:layout_width="129dp"
                android:layout_height="130dp"
                android:layout_marginTop="40dp"
                app:animateProgress="true"
                app:backgroundStrokeColor="#ff3f51b5"
                app:backgroundStrokeWidth="2dp"
                app:drawBackgroundStroke="false"
                app:foregroundStrokeCap="butt"
                app:foregroundStrokeColor="#ffff4081"
                app:foregroundStrokeWidth="3dp"
                app:indeterminate="false"
                app:indeterminateMinimumAngle="45"
                app:indeterminateRotationAnimationDuration="1200"
                app:indeterminateSweepAnimationDuration="600"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:maximum="100"
                app:progress="50"
                app:progressAnimationDuration="100"
                app:startAngle="270"
                tools:ignore="MissingConstraints"/>

            <TextView
                android:id="@+id/hum_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:gravity="center"
                android:text="@string/nan"
                android:textSize="24sp"
                app:layout_constraintBottom_toBottomOf="@+id/progress_bar_humidyty"
                app:layout_constraintEnd_toEndOf="@+id/progress_bar_humidyty"
                app:layout_constraintStart_toStartOf="@+id/progress_bar_humidyty"
                app:layout_constraintTop_toTopOf="@+id/progress_bar_humidyty" />

            <TextView
                android:id="@+id/humidity"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:text="@string/humidity"
                android:textSize="18sp"
                app:layout_constraintEnd_toEndOf="@+id/progress_bar_humidyty"
                app:layout_constraintStart_toStartOf="@+id/progress_bar_humidyty"
                app:layout_constraintTop_toBottomOf="@+id/progress_bar_humidyty"
                tools:ignore="MissingConstraints" />

            <TextView
                android:id="@+id/air"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/name_air"
                android:textSize="30sp"
                tools:layout_editor_absoluteX="0dp"
                tools:layout_editor_absoluteY="0dp"
                tools:ignore="MissingConstraints" />


        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
    </android.support.constraint.ConstraintLayout>

</LinearLayout>

name_device.xml

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="12dp">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            style="@style/MyCardViewStyle"
            android:layout_width="334dp"
            android:layout_height="121dp"
            android:layout_gravity="center"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp">

            <android.support.constraint.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <EditText
                    android:id="@+id/editNameDevice"
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    android:hint="@string/name_greenery" />

                <Button
                    android:id="@+id/buttonApply"
                    android:layout_width="match_parent"
                    android:layout_height="46dp"
                    android:layout_below="@id/editNameDevice"
                    android:layout_marginTop="48dp"
                    android:onClick="apply_click"
                    android:text="@string/apply"
                    app:layout_constraintTop_toTopOf="parent"
                    tools:ignore="MissingConstraints"
                    tools:layout_editor_absoluteX="0dp" />
            </android.support.constraint.ConstraintLayout>
        </android.support.v7.widget.CardView>
    </android.support.constraint.ConstraintLayout>
</LinearLayout>
  • Почему вы думаете, что создав совершенно другой инфлейт разметки вы получите содержимое разметки списка? вам нужно получать значение своего поля ввода непосредственно из списка. – pavlofff May 02 '18 at 02:08
  • То есть считывать надо из класса списка? – NikProst May 02 '18 at 12:48
  • https://ru.stackoverflow.com/a/446178/177345 – pavlofff May 02 '18 at 13:10
  • Спасибо большое, действительно так более логично делать. – NikProst May 02 '18 at 14:59

0 Answers0