java - 如何通过 URL 使用 setbackground 属性

标签 java android firebase-realtime-database

我想知道,如何使用 Url 来设置特定 View 的背景。 像这样的事情:

TextView someview;
someview.setbackground(url).

假设我通过模型类中的 getter 方法从 Firebase 数据库获取该 URL。

有人可以帮我清楚地理解这一点吗...

实际上,我正在尝试从我创建的 Firebase 节点加载用户状态。 下面是完整的代码和解释: 问题出在适配器类中,我在那里发表了评论,请检查...

我想从 firebase 实现的节点: enter image description here

该节点的模型类:

包 com.example.sociapp;

public class Status {

    String backgrounduri, date, fullname, profileimage, e, time, uid, userstatus;
    long textcolor, textsize;
    public Status ( )
    {

    }

    public Status(String backgrounduri, String date, String fullname, String profileimage, long textcolor, long textsize, String time, String uid, String userstatus)
    {
        this.backgrounduri = backgrounduri;
        this.date = date;
        this.fullname = fullname;
        this.profileimage = profileimage;
        this.textcolor = textcolor;
        this.textsize = textsize;
        this.time = time;
        this.uid = uid;
        this.userstatus = userstatus;
    }

    public String getBackgrounduri() {
        return backgrounduri;
    }

    public void setBackgrounduri(String backgrounduri) {
        this.backgrounduri = backgrounduri;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getProfileimage() {
        return profileimage;
    }

    public void setProfileimage(String profileimage) {
        this.profileimage = profileimage;
    }

    public long getTextcolor() {
        return textcolor;
    }

    public void setTextcolor(long textcolor) {
        this.textcolor = textcolor;
    }

    public long getTextsize() {
        return textsize;
    }

    public void setTextsize(long textsize) {
        this.textsize = textsize;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getUserstatus() {
        return userstatus;
    }

    public void setUserstatus(String userstatus) {
        this.userstatus = userstatus;
    }
}

下面是适配器类:

public class StatusAdapter extends RecyclerView.Adapter<StatusAdapter.viewHolder> {

   java.util.List<String> statuskeyList;
    List<Status> SList;
    Context context;

    DatabaseReference ClickstatusRef;
    FirebaseAuth mAuth;

    public StatusAdapter(List<String> statuskeyList, List<Status> SList, Context context)
    {
        this.statuskeyList = statuskeyList;
        this.SList = SList;
        this.context = context;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

         View view = LayoutInflater.from(context).inflate(R.layout.all_user_status_layout, parent, false);
        return new viewHolder(view);
    }

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

        Status status = SList.get(position);
        String statusKey = statuskeyList.get(position);
        mAuth = FirebaseAuth.getInstance();
        final String   CurrentUserId = mAuth.getCurrentUser().getUid();

        Picasso.get().load(status.getProfileimage()).placeholder(R.drawable.profile).into(holder.Profileimage);
        holder.FullName.setText(status.getFullname());
        holder.Date.setText(status.getDate());
        holder.Time.setText(status.getTime());
        holder.UserStatus.setText(status.getUserstatus());

        ClickstatusRef = FirebaseDatabase.getInstance().getReference().child("Status").child(statusKey);
       /* String name = status.getBackgrounduri();
        int id = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
        Drawable drawable = context.getResources().getDrawable(id);*/
       try {
           int status_background = Integer.parseInt(status.getBackgrounduri());
           holder.UserStatus.setBackgroundResource(status_background);
          }
       catch (NumberFormatException e)
              {
                  e.printStackTrace();
              }
//I tried all the code for setting background commented and not commented but no use

//问题就在这里,我在这里设置从 firebase 获取的背景 Url。我尝试了您可以在此处看到的所有代码,但没有评论 //holder.UserStatus.setBackground(context.getResources().getDrawable(context.getResources().getIdentifier("SociApp", "getBackground",context.getPackageName())));

    int status_color = (int) status.getTextcolor();
    holder.UserStatus.setTextColor(status_color);
    int Text_Size = (int)  status.getTextsize()/ 3 ;
    holder.UserStatus.setTextSize(Text_Size);


    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

         ClickstatusRef.addValueEventListener(new ValueEventListener() {
             @Override
             public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                 if (dataSnapshot.exists())
                 {
                     String statusUserId = dataSnapshot.child("uid").getValue().toString();

                     if (statusUserId.equals(CurrentUserId))
                     {
                         View mview = LayoutInflater.from(context).inflate(R.layout.dialog_layout, null);
                         TextView Message = mview.findViewById(R.id.dialog_text);
                         Button OkBtn = mview.findViewById(R.id.dialog_btn);
                         AlertDialog.Builder mbuilder = new AlertDialog.Builder(context, R.style.mydialog);
                         mbuilder.setView(mview);
                         String message = "Do you want to delete your status!";
                         Message.setText(message);
                         OkBtn.setText("Do it");
                         OkBtn.setWidth(100);
                         final Dialog dialog = mbuilder.create();
                         dialog.show();

                         OkBtn.setOnClickListener(new View.OnClickListener() {
                             @Override
                             public void onClick(View v) {

                                 ClickstatusRef.removeValue();
                                 dialog.dismiss();
                                 SendUserToLoadstatusActivity();
                             }
                         });
                     }

                     else
                     {
                         Toast.makeText(context, "You just long clicked the status", Toast.LENGTH_SHORT).show();
                     }
                 }
             }

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

             }
         });

            return true;
        }
    });

}

private void SendUserToLoadstatusActivity()
{
    Intent MainIntent = new Intent(context, LoadStatusActivity.class);
    MainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
   context.startActivity(MainIntent);
}

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

public class viewHolder extends RecyclerView.ViewHolder{

    private CircleImageView Profileimage;
    private TextView FullName;
    private TextView Date,Time;
    private TextView UserStatus;

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

        Profileimage = itemView.findViewById(R.id.status_profile_image);
        FullName = itemView.findViewById(R.id.status_user_name);
        Date = itemView.findViewById(R.id.status_date);
        Time = itemView.findViewById(R.id.status_time);
        UserStatus = itemView.findViewById(R.id.all_user_status);

    }
}

}

下面我将数据从 LoadStatusActivity 传递到数组列表:

public class LoadStatusActivity extends AppCompatActivity {

    private Toolbar mtoolbar;
    private TextView UserStatusButton;
    private RecyclerView StatusList;
    private ProgressBar ProgressCircular;

    private DatabaseReference StatusRef;
    private FirebaseAuth mAuth;

    private List<Status> mUserStatus;

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

        mtoolbar = findViewById(R.id.status_page_toolbar);
        setSupportActionBar(mtoolbar);

        mAuth = FirebaseAuth.getInstance();
        StatusList = (RecyclerView) findViewById(R.id.all_users_status_list);
        ProgressCircular = (ProgressBar) findViewById(R.id.status_progress_circular);

        StatusRef = FirebaseDatabase.getInstance().getReference().child("Status");

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Status");

        UserStatusButton = findViewById(R.id.status_post_btn);

        mUserStatus = new ArrayList();
        final List<String> Keys = new ArrayList<>();

        StatusList.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);
        StatusList.setLayoutManager(linearLayoutManager);

        UserStatusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendUserToStatusPostActivity( );
            }
        });

        Query sortStatusInDescendantOrder = StatusRef.orderByChild("counter");

        sortStatusInDescendantOrder.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                mUserStatus.clear();

                if (dataSnapshot.exists()) {

                    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                        Keys.add(dataSnapshot1.getKey());

                        Status status = dataSnapshot1.getValue(Status.class);
                        mUserStatus.add(status);

                    }

                    StatusAdapter statusAdapter = new StatusAdapter( Keys, mUserStatus, LoadStatusActivity.this);
                    StatusList.setAdapter(statusAdapter);
                    ProgressCircular.setVisibility(View.INVISIBLE);

                } else {

                    Toast.makeText(LoadStatusActivity.this, "There is no post Exists! " + DatabaseError.PERMISSION_DENIED, Toast.LENGTH_SHORT).show();
                    ProgressCircular.setVisibility(View.INVISIBLE);
                }
            }

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

            }
        });

    }

    private void SendUserToStatusPostActivity() {

        Intent StatusPostIntent = new Intent(LoadStatusActivity.this, StatusPostActivity.class);
        startActivity(StatusPostIntent);
    }
}

我得到的输出: enter image description here

但我想要带有背景的文本,而不仅仅是文本。并且背景 url 保存在 backgrounduri 中,如顶部第一张图片所示。如何加载它。 enter image description here

最佳答案

您必须下载Bitmap从给定的 URL 并设置此 Bitmap作为背景Drawable您的TextView .

下载Bitmap您必须将互联网权限添加到您的 AndroidManifest.xml

您可以下载您的Bitmap从给定的 url 中,如下所示:

try {
    // create url from string
    URL url = new URL(imageUrl);
    // connect to url
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.connect();
    // download image
    InputStream input = connection.getInputStream();
    Bitmap myBitmap = BitmapFactory.decodeStream(input);
    # return myBitmap or do something else
} catch (IOException e) {
    e.printStackTrace();
    return null;
}

设置此Bitmap作为您的背景TextView你必须将其转换为 Drawable首先使用:

// create drawable from bitmap
Drawable dr = new BitmapDrawable(myBitmap);
myTextView.setBackground(dr);

关于java - 如何通过 URL 使用 setbackground 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61252811/

相关文章:

java - 在没有FirebaseRecyclerAdapter的情况下如何增加Firebase中每个位置的viewCount?

java - 与 ThreadLocal 同步还是 InheritableThreadLocal?

java - 如何通过字节数组加载jar的整个类?

android - 无法在 android 中添加 addView

java.io.IOException : Permission denied Error when writing to removable SD card

java - 如果用户已经离开它,AsyncTask 如何仍然使用 Activity?

android - Firebase (FCM) : open activity and pass data on notification click. 安卓

java - 如何在 double 中将小数点设置为只有 2 位数字?

java - 如何将混合 Java 数据类型转换为 Java 字节数组?

ios - Swift 中的 Firebase 查询无法正常工作