Android setVisibility не работает по какой-то логике - PullRequest
0 голосов
/ 14 января 2019

Просто небольшое представление о том, что я делаю.

Я предоставляю различные функции в зависимости от типа учетной записи, с которой пользователь вошел в систему.

Тип учетной записи пользователя будет получен по ссылке Firebase из базы данных Firebase. Если вы посмотрите на это изображение, там указана стрелка. Именно здесь будет отображаться тип учетной записи, но, учитывая пользовательский интерфейс, я установил видимость текстового представления как «пропавшего». Я подтвердил, что справочные коды базы данных работают так, как если бы я установил видимость текстового представления как видимое, а затем запустил приложение, текстовое представление изменится соответственно на Администратора или Локального пользователя.

enter image description here

Проблема заключается в моей логике setVisibility 'if else'. Это не работает соответственно. Приложенный список сценариев, которые я протестировал, и его результаты.

enter image description here

Я пытался добавить видимость «ушел» на иконке карандаша и использую VISIBILE / INVISIBLE / GONE без представления перед ним (например, то, что многие говорили в качестве решения для нескольких похожих постов), но когда я попытался что значок невидим для всех 8 сценариев.

Поэтому я не уверен, что еще мне нужно сделать, чтобы преодолеть это. Любая помощь с благодарностью.


Обновление # 1: добавлены коды по запросу

class SearchViewHolder extends RecyclerView.ViewHolder {

public TextView keyword, description, acronym, relatedkeyword1, 
relatedkeyword2, relatedkeyword3, tv_rules_read_more;
public ImageView iv_rules;

public SearchViewHolder(@NonNull View itemView) {
    super(itemView);

    //knowledge feature
    keyword = itemView.findViewById(R.id.keyword);
    acronym = itemView.findViewById(R.id.acronym);
    tv_rules_read_more = itemView.findViewById(R.id.tv_rules_read_more);
    iv_rules = itemView.findViewById(R.id.iv_rules);
}
}

public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> 
implements SectionIndexer {

//    private Context context;
private List<Knowledge> knowledge;
private ArrayList<Integer> mSectionPositions;
Activity activity;
String positionUpdated;

private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;

public SearchAdapter(Activity activity, List<Knowledge> knowledge, String 
positionUpdated) {
    //this.context = context;
    this.knowledge = knowledge;
    this.activity = activity;
    this.positionUpdated = positionUpdated;
}

@NonNull
@Override
public SearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int 
viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View itemView = inflater.inflate(R.layout.layout_item, parent, false);
    return new SearchViewHolder(itemView);

}

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, final int 
position) {

    holder.keyword.setText(knowledge.get(position).getKeyword());
    holder.acronym.setText(knowledge.get(position).getAcronym());
    holder.tv_rules_read_more.setOnClickListener(new 
View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showDialog(position);
        }
    });
    if (positionUpdated != null && !positionUpdated.equals("")) {
        showDialog(Integer.parseInt(positionUpdated));
        positionUpdated = "";
    }

}

public void showDialog(final int position) {

    try {

        final Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.dialog_layout_item_rules);
        dialog.setCancelable(false);
        final TextView acctype, keyword1, description1, acronym1, 
        relatedkeyword4, relatedkeyword5, relatedkeyword6;
        //final TextView keyword1, description1, acronym1, 
        relatedkeyword4, relatedkeyword5, relatedkeyword6;
        ImageView iv_rules, iv_close_dialog, iv_edit_dialog;

        //rules feature
        acctype = dialog.findViewById(R.id.tvAccType);
        keyword1 = dialog.findViewById(R.id.keyword);
        acronym1 = dialog.findViewById(R.id.acronym);
        description1 = dialog.findViewById(R.id.description);
        relatedkeyword4 = dialog.findViewById(R.id.relatedKeyword1);
        relatedkeyword5 = dialog.findViewById(R.id.relatedKeyword2);
        relatedkeyword6 = dialog.findViewById(R.id.relatedKeyword3);
        iv_rules = dialog.findViewById(R.id.iv_rules);
        iv_close_dialog = dialog.findViewById(R.id.iv_close_dialog);
        iv_edit_dialog = dialog.findViewById(R.id.iv_edit_dialog);

        /////////
        firebaseAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();

        DatabaseReference databaseReference = 
        firebaseDatabase.getReference(firebaseAuth.getUid());
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                UserProfile userProfile = 
        dataSnapshot.getValue(UserProfile.class);
                acctype.setText(userProfile.getUserDepartment());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) 
       {
            }
        });

        if (acctype.getText().toString().equals("Administrator")){
            iv_edit_dialog.setVisibility(View.VISIBLE);
        }else {
            iv_edit_dialog.setVisibility(View.INVISIBLE);
        }
        ////////

        keyword1.setText(knowledge.get(position).getKeyword());
        description1.setText(knowledge.get(position).getDescription());
        acronym1.setText(knowledge.get(position).getAcronym());

relatedkeyword4.setText(knowledge.get(position).getRelatedkeyword1());

relatedkeyword5.setText(knowledge.get(position).getRelatedkeyword2());

relatedkeyword6.setText(knowledge.get(position).getRelatedkeyword3());
        byte[] bytesImage = knowledge.get(position).getImage();
        if (bytesImage != null && bytesImage.length > 0) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytesImage, 0, 
bytesImage.length);
            iv_rules.setImageBitmap(bitmap);
            iv_rules.setVisibility(View.VISIBLE);
        } else {
            iv_rules.setVisibility(View.GONE);
        }

        dialog.show();
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        WindowManager.LayoutParams layoutParams = new 
WindowManager.LayoutParams();
        Window window = dialog.getWindow();
        layoutParams.copyFrom(window.getAttributes());
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(layoutParams);

        iv_close_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
            }
        });

        iv_edit_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(activity, 
AddNewKnowledgeActivity.class);
                intent.putExtra("id", 
String.valueOf(knowledge.get(position).getId()));
                intent.putExtra("position", String.valueOf(position));
                intent.putExtra("call_type", "update_rule");
                intent.putExtra("title", 
knowledge.get(position).getKeyword());
                intent.putExtra("code", 
knowledge.get(position).getAcronym());
                intent.putExtra("description", 
knowledge.get(position).getDescription());
                intent.putExtra("keyword1", 
knowledge.get(position).getRelatedkeyword1());
                intent.putExtra("keyword2", 
knowledge.get(position).getRelatedkeyword2());
                intent.putExtra("keyword3", 
knowledge.get(position).getRelatedkeyword3());
                intent.putExtra("bytesImage", 
knowledge.get(position).getImage());
                dialog.cancel();
                activity.startActivityForResult(intent, 101);
            }
        });
    } catch (Exception e) {

        e.printStackTrace();
    }
}

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


@Override
public int getSectionForPosition(int position) {
    return 0;
}

@Override
public Object[] getSections() {
    List<String> sections = new ArrayList<>(26);
    mSectionPositions = new ArrayList<>(26);
    for (int i = 0, size = knowledge.size(); i < size; i++) {
        String section = 
String.valueOf(knowledge.get(i).getKeyword().charAt(0)).toUpperCase();
        if (!sections.contains(section)) {
            sections.add(section);
            mSectionPositions.add(i);
        }
    }
    return sections.toArray(new String[0]);
}

@Override
public int getPositionForSection(int sectionIndex) {
    return mSectionPositions.get(sectionIndex);
}
}

Обновление 2: добавлен файл XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#f5f0f0"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/iv_rules"
            android:layout_width="200dp"
            android:layout_height="120dp"
            android:layout_centerHorizontal="true"
            android:src="@color/deeppurpleColor"
            android:visibility="gone" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/iv_edit_dialog"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/_5sdp"
                android:background="@android:drawable/ic_menu_edit"
                android:backgroundTint="@android:color/black"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/iv_close_dialog"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/_5sdp"
                android:layout_alignParentRight="true"

android:background="@android:drawable/ic_menu_close_clear_cancel"
                android:backgroundTint="@android:color/black" />
        </LinearLayout>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp">

        <TextView
            android:id="@+id/tvAccType"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Account Type"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/keyword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:gravity="center_vertical|start"
            android:text="Baggage Management Interface Device (BMID) 
Testing 123"
            android:textAllCaps="true"
            android:textColor="#000000"
            android:textSize="15dp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/codeHeader"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:gravity="center_vertical|start"
                android:text="Code:"
                android:textColor="#a8000000"
                android:textSize="13dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/acronym"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"
                android:gravity="center_vertical|start"
                android:text="GST"
                android:textColor="#a8000000"
                android:textSize="13dp"
                android:textStyle="italic" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/ruleHeader"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:gravity="center_vertical|start"
                android:text="Desc:"
                android:textColor="#a8000000"
                android:textSize="13dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"
                android:gravity="center_vertical|start"
                android:scrollbars="vertical"
                android:text="If none are set then 'GST' is set to NULL"
                android:textColor="#a8000000"
                android:textSize="13dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/relatedKeyword"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:gravity="center_vertical|start"
                android:text="Related Keyword:"
                android:textColor="#a8000000"
                android:textSize="12sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/relatedKeyword1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"
                android:clickable="true"
                android:text="Keyword 1,"
                android:textColor="#a8000000"
                android:textSize="12sp" />

            <TextView
                android:id="@+id/relatedKeyword2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"
                android:clickable="true"
                android:text="Keyword 2,"
                android:textColor="#a8000000"
                android:textSize="12sp" />

            <TextView
                android:id="@+id/relatedKeyword3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"
                android:clickable="true"
                android:text="Keyword 3"
                android:textColor="#a8000000"
                android:textSize="12sp" />

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

1 Ответ

0 голосов
/ 21 января 2019

Проблема решается путем размещения логики if / else внутри onDataChange метода!

Логика не работала соответственно, так как моя логика if / else была размещена вне цикла. Логика должна работать, пока Firebase извлекает и отображает значения.

Таким образом, вместо этих:

        DatabaseReference databaseReference = 
    firebaseDatabase.getReference(firebaseAuth.getUid());
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            UserProfile userProfile = 
    dataSnapshot.getValue(UserProfile.class);
            acctype.setText(userProfile.getUserDepartment());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) 
   {
        }
    });

    //note: these are outside of the loop at first
    if (acctype.getText().toString().equals("Administrator")){
        iv_edit_dialog.setVisibility(View.VISIBLE);
    }else {
        iv_edit_dialog.setVisibility(View.INVISIBLE);
    }

Вместо этого должно быть так:

        DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
                acctype.setText(userProfile.getUserDepartment());

                //granting different functionality based on account type
                if (acctype.getText().toString().equals("Administrator")){
                    iv_edit_dialog.setVisibility(View.VISIBLE);
                }else {
                    iv_edit_dialog.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });

Я усвоил свой урок трудным путем! очень важно понять логику, с которой вы хотите выйти, а затем ожидаемый рабочий процесс!

Огромное спасибо тем, кто нашел время, чтобы провести меня!

...