0

我正在为网站bayfiles.net 创建一个应用程序我有一个可以接收json 数据的工作列表视图。这适用于文件名和大小,现在我也有一个 ImageView。我想确定应该将哪个图标放在图标支架中。这是由文件名的结尾决定的。例如,以“.png”结尾的文件名应该显示带有“png”文本的图标。是怎么做的?

这是我的工作活动:

public class FilesActivity extends SherlockActivity {

    EditText editsearch;
    fileObjectAdapter adapter;
    String httpurl, sessionId, filetype;

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

        ActionBar abs = getSupportActionBar();
        abs.setDisplayHomeAsUpEnabled(false);
        abs.setTitle("BAYFILES");
        //abs.setIcon(R.drawable.abs_logo);
        abs.setDisplayShowCustomEnabled(true);

        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        View customNav = LayoutInflater.from(this).inflate(R.layout.actionbar, null);
        abs.setCustomView(customNav, lp);
        abs.setDisplayShowCustomEnabled(true);

        abs.setDisplayOptions(abs.DISPLAY_SHOW_HOME|abs.DISPLAY_SHOW_CUSTOM);
        abs.setDisplayShowTitleEnabled(true);

        Crouton.makeText(this, "You have been signed in!", Style.CONFIRM).show();

        ImageButton btnSearch = (ImageButton) findViewById(R.id.action_search);
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("Button Click","position");
            }
        });

        Context context = getApplicationContext();
        AppPrefs appPrefs = new AppPrefs(context);
        sessionId = appPrefs.getSessionId();
        newRequest("http://api.bayfiles.net/v1/account/files?session=" + sessionId);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        com.actionbarsherlock.view.MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.menu, (com.actionbarsherlock.view.Menu) menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId())
        {
        case R.id.refresh:
            newRequest("http://api.bayfiles.net/v1/account/files?session=" + sessionId);
            return true;

        case R.id.settings:
            Intent startNewActivityOpen = new Intent(FilesActivity.this, AccountActivity.class);
             startActivityForResult(startNewActivityOpen, 0);
            return true;

        case R.id.upload:
            Crouton.makeText(this, "Coming soon!", Style.INFO).show();
            return true;

        case R.id.link:
            Crouton.makeText(this, "Add link from BayFiles", Style.INFO).show();
            return true;

        case R.id.folder:
            Crouton.makeText(this, "Not available yet!", Style.INFO).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onContextItemSelected(android.view.MenuItem item) {
        switch(item.getItemId()){
        case R.id.info:
            Crouton.makeText(this, "Coming soon!", Style.INFO).show();
            Log.d("log_tag", "Info");
            break;
        case R.id.delete:
            new RequestTask().execute(httpurl);
            newRequest("http://api.bayfiles.net/v1/account/files?session=" + sessionId);
            break;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflate = getMenuInflater();
        inflate.inflate(R.menu.context_menu, menu);
    }

    public static String readableFileSize(long size) {
        if(size <= 0) return "0";
        final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
        int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    public void newRequest(String url){
        String response = null;
        DefaultHttpClient httpClient = new DefaultHttpClient();
        ResponseHandler <String> resonseHandler = new BasicResponseHandler();
        HttpPost postMethod = new HttpPost(url);

        try {
            JSONObject json = new JSONObject();

               postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
               postMethod.setHeader( "Content-Type", "application/json" );
               response = httpClient.execute(postMethod,resonseHandler);
               JSONObject request = new JSONObject(response);

               ArrayList<fileObject> objectList = new ArrayList<fileObject>();

               for (Iterator<?> keyIterator = request.keys(); keyIterator.hasNext(); ) {
                   String key = (String) keyIterator.next();
                   JSONObject object = request.optJSONObject(key);

                   if (object != null) {
                       long l = Long.parseLong(object.getString("size"));
                       String size = readableFileSize(l);
                       String[] filetype = object.getString("filename").split("\\.");
                       Log.d("log_tag", filetype[1]);

                       fileObject obj = new fileObject();

                       obj.setFileId(key);
                       obj.setFileName(object.getString("filename"));
                       obj.setSize(size);
                       obj.setInfoToken(object.getString("infoToken"));
                       obj.setDeleteToken(object.getString("deleteToken"));
                       obj.setSha1(object.getString("sha1"));
                       obj.setFileType(filetype[1]);
                       objectList.add(obj);

                   }
               }        
               final ListView lv1 = (ListView) findViewById(R.id.listobjects);
               lv1.setAdapter(new fileObjectAdapter(this, objectList));
               lv1.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                    Object o = lv1.getItemAtPosition(position);
                    fileObject fullObject = (fileObject) o;
                    Log.d("log_tag", "Filename: " + fullObject.getFileName());
                    httpurl = "http://bayfiles.net/file/" + fullObject.getFileId() + "/" + fullObject.getInfoToken() + "/" + fullObject.getFileName();
                }  
               });

               lv1.setOnItemLongClickListener(new OnItemLongClickListener() {

                   public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
                       registerForContextMenu(lv1); 
                       openContextMenu(lv1);

                       Object o = lv1.getItemAtPosition(position);
                       fileObject fullObject = (fileObject) o;
                       httpurl = "http://api.bayfiles.net/v1/file/delete/" + fullObject.getFileId() + "/" + fullObject.getDeleteToken();
                       return true;
                   }
               }); 
        }
        catch(Exception e)
        {      
            e.printStackTrace();
            Log.d("log_tag", "Error: " + e.toString());

        }
    }
}

我的文件对象:

package com.spxc.bayfiles.adapter;

    public class fileObject {

        private String fileName;
        private String size;
        private String infoToken;
        private String deleteToken;
        private String sha1;
        private String fileId;
        private String fileType;

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getSize() {
            return size;
        }

        public void setSize(String size) {
            this.size = size;
        }

        public String getInfoToken() {
            return infoToken;
        }

        public void setInfoToken(String infoToken) {
            this.infoToken = infoToken;
        }

        public String getDeleteToken() {
            return deleteToken;
        }

        public void setDeleteToken(String deleteToken) {
            this.deleteToken = deleteToken;
        }

        public String getSha1() {
            return sha1;
        }

        public void setSha1(String sha1) {
            this.sha1 = sha1;
        }

        public String getFileId() {
            return fileId;
        }

        public void setFileId(String fileId) {
            this.fileId = fileId;
        }
        public String getFileType(){
            return fileType;
        }
        public void setFileType(String fileType){
            this.fileType = fileType;
        }
    }

还有我的适配器:

public class fileObjectAdapter extends BaseAdapter {
     private static ArrayList<fileObject> searchArrayList;

     private LayoutInflater mInflater;

     public fileObjectAdapter(Context context, ArrayList<fileObject> results) {
      searchArrayList = results;
      mInflater = LayoutInflater.from(context);
     }

     public int getCount() {
      return searchArrayList.size();
     }

     public Object getItem(int position) {
      return searchArrayList.get(position);
     }

     public long getItemId(int position) {
      return position;
     }

     public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      if (convertView == null) {
       convertView = mInflater.inflate(R.layout.dbitems, null);
       holder = new ViewHolder();
       holder.txtFileName = (TextView) convertView.findViewById(R.id.size);
       holder.txtSize = (TextView) convertView.findViewById(R.id.filename);
       holder.imgIcon = (ImageView) convertView.findViewById(R.id.typeimg);

       convertView.setTag(holder);
      } else {
       holder = (ViewHolder) convertView.getTag();
      }

      holder.txtFileName.setText(searchArrayList.get(position).getFileName());
      holder.txtSize.setText(searchArrayList.get(position).getSize());
      //holder.imgIcon.setImageResource(SET DRAWABLE ACCORDING TO ENDING);

      return convertView;
     }

     static class ViewHolder {
      TextView txtFileName;
      TextView txtSize;
      ImageView imgIcon;
     }
     public void filter(String charText) {
            charText = charText.toLowerCase(Locale.getDefault());
            searchArrayList.clear();
            if (charText.length() == 0) {
                searchArrayList.addAll(searchArrayList);
            } 
            else
            {
                for (fileObject wp : searchArrayList) 
                {
                    if (wp.getFileName().toLowerCase(Locale.getDefault()).contains(charText)) 
                    {
                        searchArrayList.add(wp);
                    }
                }
            }
            notifyDataSetChanged();
        }
    }

如您所见,我得到了完整的文件名并将其分成两部分。文件名和扩展名。然后我会做一个 if 语句来检查它是哪个文件扩展名。然后我希望它根据文件扩展名更改列表项中的图标。如何才能做到这一点?

任何帮助深表感谢!

4

1 回答 1

0

如果我误解了你的问题,我深表歉意。可以肯定的是,我已经经历了几次,但我的解决方案相对简单,而且由于您似乎知道自己在代码中做了什么,我很惊讶您还没有得到这个。所以,如果我误解了,我再次道歉。

您需要在 ImageView 上设置可绘制资源。这非常简单,但第一部分是如果您希望在各种屏幕分辨率上看起来不错,您需要在 /res 文件夹中拥有几个不同的版本。您基本上需要将图像缩放到相应文件夹中的不同分辨率。MDPI = 1.0X,HDPI = 1.5X,XHDPI = 2.0X。

因此,假设您有一张要显示为 .exe 文件扩展名的图片。您将为 MDPI 制作基本 72 分辨率的文件,然后为 HDPI 和 XHDPI 创建缩放版本。假设您将图片文件命名为 exe_picture.png。您将在每个文件夹中放置名为 exe_picture 的相应文件。然后,您可以在适配器 getView 函数中以编程方式引用图像并将其放置在 ImageView 中(请注意以下代码未经测试):

holder.txtFileName.setText(searchArrayList.get(position).getFileName());
holder.txtSize.setText(searchArrayList.get(position).getSize());

String fileType = searchArrayList.get(position).getFileType();
int imageResID = 0;
if (fileType.equals("exe")) {
    imageResID = R.drawable.exe_picture;
}

holder.imgIcon.setImageResource(imageResID);

当然,您可以从那里简单地将 else if 语句链接到您想要支持的所有文件类型。

希望这可以帮助!祝你好运。

于 2013-07-22T21:55:25.903 回答