无法更新cardView

时间:2018-02-26 10:22:35

标签: android material-design

我无法在我的应用中更新cardView。我有一个主要活动,显示我的卡片视图,其中包含textviewseekbarimageViewswitch。我有一个编辑活动来编辑卡片和一个添加活动来添加新卡片。我在onClickListener课程的Itemview上添加了ViewHolder,其中startactivityforresult intent Transitioneditactivity transitioneditactivitypublic class MainActivity extends AppCompatActivity { public static final String TRANSITION_FAB = "fab_transition"; public static final String EXTRA_NAME = "name"; public static final String EXTRA_TYPE = "type"; public static final String EXTRA_SEEK = "seek"; public static final String EXTRA_UPDATE = "update"; public static final String EXTRA_DELETE = "delete"; private RecyclerView recyclerView; private CardAdapter adapter; private ArrayList<Card> cardsList=new ArrayList<>(); private String[] names; private int[] type; private String[] type_name; private boolean[] switchstates; private boolean[] seekstatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); names=getResources().getStringArray(R.array.device); type_name = getResources().getStringArray(R.array.appliances); initcards(); if(adapter==null){ adapter=new CardAdapter(this,cardsList); } recyclerView=findViewById(R.id.recyclerview); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); FloatingActionButton fab=findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Pair<View,String> pair=Pair.create(view.findViewById(R.id.fab),TRANSITION_FAB); ActivityOptions options; Activity act= MainActivity.this; options= ActivityOptions.makeSceneTransitionAnimation(act,pair); Intent transitionIntent= new Intent(act,TransitionAddActivity.class); act.startActivityForResult(transitionIntent,adapter.getItemCount(),options.toBundle()); } }); } public void doSmoothScroll(int position){ recyclerView.smoothScrollToPosition(position); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==adapter.getItemCount()){ if(resultCode==RESULT_OK){ String name =data.getStringExtra(EXTRA_NAME); int type=data.getIntExtra(EXTRA_TYPE,0); boolean seek = data.getBooleanExtra(EXTRA_SEEK,false); adapter.addCard(name,type,false,seek); }else { if (resultCode==RESULT_OK){ RecyclerView.ViewHolder viewHolder=recyclerView.findViewHolderForAdapterPosition(requestCode); if(data.getExtras().getBoolean(EXTRA_UPDATE)){ String name = data.getStringExtra(EXTRA_NAME); int type = data.getIntExtra(EXTRA_TYPE,0); boolean seek = data.getBooleanExtra(EXTRA_SEEK,false); viewHolder.itemView.setVisibility(View.INVISIBLE); adapter.updateCard(name,type,seek,requestCode); } } } } } private void initcards() { for(int i=0;i<2;i++){ Card card=new Card(); card.setId((long)i); card.setName(names[i]); card.setStatus(false); card.setType(i); cardsList.add(card); } } } 是用户可以编辑值的位置,然后按“保存”以反映更改。但是,更改未反映在应用程序中。我正在关注Android应用程序开发的书籍介绍中的代码,他们已经做了同样的事情,但他们的工作和我的工作没有。

继承代码

MainActivity

public class Card {

private long id;
private String name;
private int type;
private boolean status;
private boolean seekstatus;

public long getId() {
    return id;
}

public boolean isSeekstatus() {
    return seekstatus;
}

public void setSeekstatus(boolean seekstatus) {
    this.seekstatus = seekstatus;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getType() {
    return type;
}

public void setType(int type) {
    this.type = type;
}

public boolean isStatus() {
    return status;
}

public void setStatus(boolean status) {
    this.status = status;
}
}

继承卡类

public class CardAdapter extends 
RecyclerView.Adapter<CardAdapter.ViewHolder>{
private static final String DEBUG_TAG = "CardAdapter";

public Context context;
public ArrayList<Card> cardsList;


public CardAdapter(Context context, ArrayList<Card> cardsList){
    this.context=context;
    this.cardsList=cardsList;
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    String name1 = cardsList.get(position).getName();
    boolean switchstatus=cardsList.get(position).isStatus();
    boolean seekstatus=cardsList.get(position).isSeekstatus();
    int type=cardsList.get(position).getType();
    TextView nametv= viewHolder.name;
    nametv.setText(name1);
    Switch device_switch = viewHolder.device_switch;
    device_switch.setChecked(switchstatus);
    SeekBar seek = viewHolder.seekbar;
    if(seekstatus){
        seek.setVisibility(View.VISIBLE);
    }else {
        seek.setVisibility(View.INVISIBLE);
    }
}

@Override
public void onViewDetachedFromWindow(ViewHolder holder) {
    super.onViewDetachedFromWindow(holder);
    holder.itemView.clearAnimation();
}
@Override
public void onViewAttachedToWindow(ViewHolder holder) {
    super.onViewAttachedToWindow(holder);
    animateCircularReveal(holder.itemView);
}

public void animateCircularReveal(View view){
    int centerX=0;
    int centerY=0;
    int startRadius=0;
    int endRadius=Math.max(view.getWidth(),view.getHeight());
    Animator animation=ViewAnimationUtils.createCircularReveal(view,centerX,centerY,startRadius,endRadius);
    view.setVisibility(View.VISIBLE);
    animation.start();
}

public void animateCircularDelete(final View view,final int list_position){
    int centerX=view.getWidth();
    int centerY=view.getHeight();
    int startRadius=view.getWidth();
    int endRadius=0;
    Animator animation = ViewAnimationUtils.createCircularReveal(view,centerX,centerY,startRadius,endRadius);
    animation.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            view.setVisibility(View.GONE);
            cardsList.remove(list_position);
            notifyItemRemoved(list_position);
        }
    });
}
public void addCard(String name,int type,boolean switchstatus,boolean seekstatus){
    Card card=new Card();
    card.setName(name);
    card.setType(type);
    card.setStatus(switchstatus);
    card.setSeekstatus(seekstatus);
    ((MainActivity)context).doSmoothScroll(getItemCount());
    cardsList.add(card);
    notifyItemInserted(getItemCount());
}

public void updateCard(String name,int type,boolean seekstatus,int list_position){
    cardsList.get(list_position).setName(name);
    cardsList.get(list_position).setType(type);
    cardsList.get(list_position).setSeekstatus(seekstatus);
    notifyItemChanged(list_position);
}

public void deleteCard(View view,int list_position){
    animateCircularDelete(view,list_position);
}

@Override
public int getItemCount() {
    if(cardsList.isEmpty()){
        return 0;
    } else {
        return cardsList.size();
    }
}


@Override
public long getItemId(int position) {
    return cardsList.get(position).getId();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    LayoutInflater li=LayoutInflater.from(viewGroup.getContext());
    View v=li.inflate(R.layout.card_view_holder,viewGroup,false);
    return new ViewHolder(v);
}

public class ViewHolder extends RecyclerView.ViewHolder{

    private TextView name;
    private Switch device_switch;
    private ImageView device_image;
    private SeekBar seekbar;

    public ViewHolder(View v) {
        super(v);
        name=v.findViewById(R.id.name);
        device_image=v.findViewById(R.id.device_image);
        device_switch=v.findViewById(R.id.device_switch);
        seekbar=v.findViewById(R.id.seekbar);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int requestCode= getAdapterPosition();
                String name = cardsList.get(requestCode).getName();
                int type = cardsList.get(requestCode).getType();
                boolean seekstatus=cardsList.get(requestCode).isSeekstatus();
                Intent transitionIntent=new Intent(context,TransitionEditActivity.class);
                transitionIntent.putExtra(MainActivity.EXTRA_NAME,name);
                transitionIntent.putExtra(MainActivity.EXTRA_TYPE,type);
                transitionIntent.putExtra(MainActivity.EXTRA_SEEK,seekstatus);
                transitionIntent.putExtra(MainActivity.EXTRA_UPDATE,false);
                transitionIntent.putExtra(MainActivity.EXTRA_DELETE,false);
                ((AppCompatActivity)context).startActivityForResult(transitionIntent,requestCode);
            }
        });

        device_switch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText((context),""+name.getText()+" is turned "+(device_switch.isChecked()?"On":"Off"),Toast.LENGTH_SHORT).show();
            }
        });
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                Toast.makeText((context),""+name.getText()+"is set at "+i+"%",Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar){
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }
}
}

CardAdapter类

public class TransitionEditActivity extends AppCompatActivity {

private EditText device_name;
private Spinner device_type;
private CheckBox seek_status;
ArrayAdapter<CharSequence> adapter;
private int type;

Button savebutton;

private Intent intent;

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

    device_name =findViewById(R.id.name);
    device_type=findViewById(R.id.type);
    seek_status=findViewById(R.id.cbintensity);
    savebutton=findViewById(R.id.add);
    adapter= ArrayAdapter.createFromResource(this,R.array.appliances,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    device_type.setAdapter(adapter);

    device_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
            type = i;
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });



    intent=getIntent();
    String name=intent.getStringExtra(MainActivity.EXTRA_NAME);
    type=intent.getIntExtra(MainActivity.EXTRA_TYPE,0);
    boolean seek=intent.getBooleanExtra(MainActivity.EXTRA_SEEK,false);

    device_name.setText(name);
    device_name.setSelection(device_name.getText().length());

    seek_status.setChecked(seek);

    savebutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(TextUtils.isEmpty(device_name.getText().toString().trim())){
                Toast.makeText(getApplicationContext(),"Enter a valid name",Toast.LENGTH_SHORT).show();
            }else {
                intent.putExtra(MainActivity.EXTRA_NAME,String.valueOf(device_name.getText()));
                intent.putExtra(MainActivity.EXTRA_TYPE,type);
                intent.putExtra(MainActivity.EXTRA_SEEK,seek_status.isChecked());
                intent.putExtra(MainActivity.EXTRA_UPDATE,true);
                setResult(RESULT_OK,intent);
                supportFinishAfterTransition();
            }
        }
    });


}

}

EditActivity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="kejriwal.shivam.automationcard.MainActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
<android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="25dp"
    android:layout_marginEnd="25dp"
    android:elevation="6dp"
    android:contentDescription="Add appliance"
    android:id="@+id/fab"
    android:clickable="true"
    android:src="@android:drawable/ic_input_add"
    android:tint="@android:color/white"
    android:layout_height="wrap_content" />




</RelativeLayout>

我的活动主布局文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/card_layout"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:clickable="true"
android:layout_marginTop="10dp"
android:focusable="true"
android:elevation="6dp"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="vertical"
card_view:cardBackgroundColor="@color/card"
card_view:cardCornerRadius="3dp"
>

<LinearLayout
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:id="@+id/linear"
    android:orientation="vertical"
    android:padding="3dp"
    android:layout_height="match_parent">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <ImageView
            android:id="@+id/device_image"
            android:src="@android:drawable/ic_input_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_marginStart="10dp"
            android:layout_marginTop="10dp"
            android:layout_centerVertical="true"
            />
        <TextView
            android:id="@+id/name"
            android:text="Fan"
            android:layout_marginStart="20dp"
            android:layout_toRightOf="@+id/device_image"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/device_image"
            android:textSize="20sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Switch
            android:id="@+id/device_switch"
            android:layout_marginEnd="10dp"
            android:layout_centerVertical="true"
            android:layout_gravity="end"
            android:layout_marginRight="20dp"
            android:layout_width="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_height="wrap_content" />
    </RelativeLayout>
    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:layout_marginEnd="90dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="10dp"
        />

</LinearLayout>
</LinearLayout>

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

卡片布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_margin="20dp"
android:layout_height="match_parent"
android:orientation="vertical"
>

<ImageView
    android:layout_width="50dp"
    android:id="@+id/device_image"
    android:layout_gravity="center"
    android:layout_height="50dp"
    android:layout_marginBottom="20dp"
    />
<EditText
    android:layout_width="200dp"
    android:id="@+id/name"
    android:layout_gravity="center"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    />
<Spinner
    android:layout_width="wrap_content"
    android:prompt="@string/spinner_prompt"
    android:layout_gravity="center"
    android:layout_height="wrap_content"
    android:id="@+id/type"
    android:layout_marginBottom="20dp"
    android:entries="@array/appliances"
    />
<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Control Intensity"
    android:id="@+id/cbintensity"
    />
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content"
        android:text="Save"/>
</RelativeLayout>

</LinearLayout>

编辑布局文件

var a = [1,2,3]
let ptr1 = UnsafeMutablePointer<Int>(&a[0]) //works fine

let index = 0
let ptr2 = UnsafeMutablePointer<Int>(&a[index]) //compiler throws error

1 个答案:

答案 0 :(得分:0)

您正在适配器的视图中绑定数据...

你的适配器应该是这样的......

public class BorderAdapter extends RecyclerView.Adapter<BorderAdapter.ViewHolder> {
    private final Context context;
    private final BorderSelectedListener borderSelectedListener;

    public BorderAdapter(Context context, BorderSelectedListener borderSelectedListener) {
        this.context = context;
        this.borderSelectedListener = borderSelectedListener;
    }

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(this.context).inflate(R.layout.frames_adapter_item, parent, false));
    }

    public void onBindViewHolder(final ViewHolder holder, @SuppressLint("RecyclerView") int position) {

        Animation animation = AnimationUtils.loadAnimation(context,
                (position > lastPosition) ? R.anim.left_to_right
                        : R.anim.right_to_left);
        holder.itemView.startAnimation(animation);
        holder.imageView.setBackground(context.getResources().getDrawable(R.drawable.stroke_invisible));

        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                borderSelectedListener.onBorderSelected(holder.getAdapterPosition());

            }
        });

    }

    public int getItemCount() {

        return serverData.getBorderFramesDetail().size();

    }

    public interface BorderSelectedListener {
        void onBorderSelected(int position);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        final ImageView imageView;
        final ProgressBar progress_bar;

        ViewHolder(View itemView) {
            super(itemView);
            this.imageView = itemView.findViewById(R.id.imageView);
            this.progress_bar = itemView.findViewById(R.id.progress_bar);
        }
    }
}