Iconified TextList - The making of

Iconified TextList - The making of

What you will learn: You will learn how to create your own ListAdapter: IconifiedListAdapter

Question Problems/Questions: Write it right below...

Difficulty: 1.5 of 5 Smile

What it will look like:


Description:
The app (screenshot above) is created with the following simple code. So that is what we finally want to reach:
Java:
       IconifiedTextListAdapter itla = new IconifiedTextListAdapter ( this );

        // Add four items
        itla. addItem ( new IconifiedText (
                "Surf Web", getResources ( ). getDrawable (R. drawable. favicon ) ) );
        itla. addItem ( new IconifiedText (
                "Report Bug", getResources ( ). getDrawable (R. drawable. bug ) ) );
        itla. addItem ( new IconifiedText (
                "Speak Spanish", getResources ( ). getDrawable (R. drawable. locale ) ) );
        itla. addItem ( new IconifiedText (
                "Vidoop", getResources ( ). getDrawable (R. drawable. vidoop ) ) );
        // Display it
        setListAdapter (itla );


We simply create an: IconifiedTextListAdapter, throw some String+Drawable into and 'display it. To use such awesome simple code, we need to do some work.

1. Lets start with the very Base: The IconifiedText.java which is a pretty small class, which only contains a simply constructor and some getters & setters. It is only a class that combines a String and a Drawable(Icon), nothing special!

Java:
public class IconifiedText {
   
      private String mText = "";
      private Drawable mIcon;
      private boolean mSelectable = true;

      public IconifiedText ( String text, Drawable bullet ) {
          mIcon = bullet;
          mText = text;
      }
      // ...
}


2. Now we take a look at the IconifiedTextListAdapter.java which consists of about 50 Lines of Code, but does not much. It basically is a storage for a list of IconifiedTexts, to which you can "add(IconifiedText);", and that passes through some functions to the elements of the IconifiedText-List, like 'getItem(int position)' or 'isSelectable(int position)'.
Being an (specialized) Adapter , the second thing to provide a function through which one can access the views (all the things) it contains:
Java:
      /** @param convertView The old view to overwrite, if one is passed
      * @returns a IconifiedTextView that holds wraps around an IconifiedText */

      public View getView ( int position, View convertView, ViewGroup parent ) {
          IconifiedTextView btv;
           if (convertView == null ) {
               btv = new IconifiedTextView (mContext, mItems. get (position ) );
           } else { // Reuse/Overwrite the View passed
                // We are assuming(!) that it is castable!
               btv = (IconifiedTextView ) convertView;
               btv. setText (mItems. get (position ). getText ( ) );
               btv. setIcon (mItems. get (position ). getIcon ( ) );
           }
           return btv;
      }

That was probably also not too hard to understand (if so, ask for explanation below).

3.The IconifiedTextView is also not too hard to understand.
It extends LinearLayout. Neutral
Idea Lets remember, that GUIs in Android are nested. ( A view, can contain a View, can contain a View, can contain a View, can contain a View, can contain a View...)
Arrow So it will be no problem, that our IconifiedTextView itself consists of two more Views, aIconView and a TextView.
The IconifiedTextView does it own setup in the Constructor:
Java:
      public IconifiedTextView ( Context context, IconifiedText aIconifiedText ) {
           super (context );

           /* First Icon and the Text to the right (horizontal),
           * not above and below (vertical) */

           this. setOrientation (HORIZONTAL );

          mIcon = new ImageView (context );
          mIcon. setImageDrawable (aIconifiedText. getIcon ( ) );
           // left, top, right, bottom
          mIcon. setPadding ( 0, 2, 5, 0 ); // 2px up, 5px to the right
          
           /* At first, add the Icon to ourself
           * (! we are extending LinearLayout) */

          addView (mIcon,   new LinearLayout. LayoutParams (
                    LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT ) );
          
          mText = new TextView (context );
          mText. setText (aIconifiedText. getText ( ) );
           /* Now the text (after the icon) */
          addView (mText, new LinearLayout. LayoutParams (
                    LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT ) );
      }


So thats it =). You successfully created an IconifiedTextList(Adapter) Exclamation

The full source:

Arrow Arrow Icons (res/drawable/*.png) used in Demo App Exclamation

'src/your_package_structure/TestLayout.java'
Java:
/* $Id: TestLayout.java 57 2007-11-21 18:31:52Z steven $
 *
 * Copyright 2007 Steven Osborn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org. anddev. android. testproject;

import android. app. ListActivity;
import android. os. Bundle;

public class TestLayout extends ListActivity {

    @Override
    public void onCreate (Bundle icicle ) {
        super. onCreate (icicle );
        IconifiedTextListAdapter itla = new IconifiedTextListAdapter ( this );

        // Add four items
        itla. addItem ( new IconifiedText (
                "Surf Web", getResources ( ). getDrawable (R. drawable. favicon ) ) );
        itla. addItem ( new IconifiedText (
                "Report Bug", getResources ( ). getDrawable (R. drawable. bug ) ) );
        itla. addItem ( new IconifiedText (
                "Speak Spanish", getResources ( ). getDrawable (R. drawable. locale ) ) );
        itla. addItem ( new IconifiedText (
                "Vidoop", getResources ( ). getDrawable (R. drawable. vidoop ) ) );
        // Display it
        setListAdapter (itla );
    }
}


'src/your_package_structure/IconifiedText.java'
Java:
/*
 * Copyright 2007 Steven Osborn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org. anddev. android. testproject;

import android. graphics. drawable. Drawable;

/** @author Steven Osborn - http://steven.bitsetters.com */
public class IconifiedText implements Comparable<IconifiedText> {
   
      private String mText = "";
      private Drawable mIcon;
      private boolean mSelectable = true;

      public IconifiedText ( String text, Drawable bullet ) {
          mIcon = bullet;
          mText = text;
      }
     
      public boolean isSelectable ( ) {
           return mSelectable;
      }
     
      public void setSelectable ( boolean selectable ) {
          mSelectable = selectable;
      }
     
      public String getText ( ) {
           return mText;
      }
     
      public void setText ( String text ) {
          mText = text;
      }
     
      public void setIcon (Drawable icon ) {
          mIcon = icon;
      }
     
      public Drawable getIcon ( ) {
           return mIcon;
      }

      /** Make IconifiedText comparable by its name */
     @Override
      public int compareTo (IconifiedText other ) {
           if ( this. mText != null )
                return this. mText. compareTo (other. getText ( ) );
           else
                throw new IllegalArgumentException ( );
      }
}


'src/your_package_structure/IconifiedTextView.java'
Java:
/* $Id: BulletedTextView.java 57 2007-11-21 18:31:52Z steven $
 *
 * Copyright 2007 Steven Osborn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org. anddev. android. testproject;

import android. content. Context;
import android. graphics. drawable. Drawable;
import android. widget. ImageView;
import android. widget. LinearLayout;
import android. widget. TextView;

public class IconifiedTextView extends LinearLayout {
     
      private TextView mText;
      private ImageView mIcon;
     
      public IconifiedTextView ( Context context, IconifiedText aIconifiedText ) {
           super (context );

           /* First Icon and the Text to the right (horizontal),
           * not above and below (vertical) */

           this. setOrientation (HORIZONTAL );

          mIcon = new ImageView (context );
          mIcon. setImageDrawable (aIconifiedText. getIcon ( ) );
           // left, top, right, bottom
          mIcon. setPadding ( 0, 2, 5, 0 ); // 5px to the right
          
           /* At first, add the Icon to ourself
           * (! we are extending LinearLayout) */

          addView (mIcon,   new LinearLayout. LayoutParams (
                    LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT ) );
          
          mText = new TextView (context );
          mText. setText (aIconifiedText. getText ( ) );
           /* Now the text (after the icon) */
          addView (mText, new LinearLayout. LayoutParams (
                    LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT ) );
      }

      public void setText ( String words ) {
          mText. setText (words );
      }
     
      public void setIcon (Drawable bullet ) {
          mIcon. setImageDrawable (bullet );
      }
}


'src/your_package_structure/IconifiedTextListAdapter.java'
Java:
/* $Id: BulletedTextListAdapter.java 57 2007-11-21 18:31:52Z steven $
 *
 * Copyright 2007 Steven Osborn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org. anddev. android. testproject;

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

import android. content. Context;
import android. view. View;
import android. view. ViewGroup;
import android. widget. BaseAdapter;

/** @author Steven Osborn - http://steven.bitsetters.com */
public class IconifiedTextListAdapter extends BaseAdapter {

      /** Remember our context so we can use it when constructing views. */
      private Context mContext;

      private List<IconifiedText> mItems = new ArrayList<IconifiedText> ( );

      public IconifiedTextListAdapter ( Context context ) {
          mContext = context;
      }

      public void addItem (IconifiedText it ) { mItems. add (it ); }

      public void setListItems (List<IconifiedText> lit ) { mItems = lit; }

      /** @return The number of items in the */
      public int getCount ( ) { return mItems. size ( ); }

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

      public boolean areAllItemsSelectable ( ) { return false; }

      public boolean isSelectable ( int position ) {
           try {
                return mItems. get (position ). isSelectable ( );
           } catch ( IndexOutOfBoundsException aioobe ) {
                return super. isSelectable (position );
           }
      }

      /** Use the array index as a unique id. */
      public long getItemId ( int position ) {
           return position;
      }

      /** @param convertView The old view to overwrite, if one is passed
      * @returns a IconifiedTextView that holds wraps around an IconifiedText */

      public View getView ( int position, View convertView, ViewGroup parent ) {
          IconifiedTextView btv;
           if (convertView == null ) {
               btv = new IconifiedTextView (mContext, mItems. get (position ) );
           } else { // Reuse/Overwrite the View passed
                // We are assuming(!) that it is castable!
               btv = (IconifiedTextView ) convertView;
               btv. setText (mItems. get (position ). getText ( ) );
               btv. setIcon (mItems. get (position ). getIcon ( ) );
           }
           return btv;
      }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
抱歉,我在之前的代码中犯了一个错误。请尝试将`origin`变量的声明移动到`CustomWindow`类的顶部,如下所示: java import java.awt.*; import javax.swing.*; import java.awt.event.*; public class CustomWindow extends JFrame { private JPanel titleBarPanel; private JButton minimizeButton; private JButton maximizeButton; private JButton closeButton; private Point origin; public CustomWindow() { // 设置窗口大小和背景色 this.setSize(1100, 700); this.getContentPane().setBackground(new Color(204, 204, 204)); // 去除窗口边框默认样式 this.setUndecorated(true); // 禁用窗口缩放 this.setResizable(false); // 居中显示窗口 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; int windowWidth = this.getWidth(); int windowHeight = this.getHeight(); int x = (screenWidth - windowWidth) / 2; int y = (screenHeight - windowHeight) / 2; this.setLocation(x, y); // 鼠标可以移动窗口 titleBarPanel = new JPanel(); titleBarPanel.setBackground(Color.WHITE); titleBarPanel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { origin = new Point(e.getX(), e.getY()); } @Override public void mouseReleased(MouseEvent e) { origin = null; } }); titleBarPanel.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { Point p = getLocation(); setLocation(p.x + e.getX() - origin.x, p.y + e.getY() - origin.y); } }); // 添加最小化、最大化和关闭按钮 minimizeButton = new JButton(new ImageIcon("minimize.png")); maximizeButton = new JButton(new ImageIcon("maximize.png")); closeButton = new JButton(new ImageIcon("close.png")); minimizeButton.setBorderPainted(false); maximizeButton.setBorderPainted(false); closeButton.setBorderPainted(false); minimizeButton.setOpaque(false); maximizeButton.setOpaque(false); closeButton.setOpaque(false); minimizeButton.setContentAreaFilled(false); maximizeButton.setContentAreaFilled(false); closeButton.setContentAreaFilled(false); // 添加按钮功能 minimizeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setExtendedState(JFrame.ICONIFIED); } }); maximizeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (getExtendedState() != JFrame.MAXIMIZED_BOTH) { setExtendedState(JFrame.MAXIMIZED_BOTH); } else { setExtendedState(JFrame.NORMAL); } } }); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); // 高亮按钮 minimizeButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { minimizeButton.setIcon(new ImageIcon("minimize_highlight.png")); } @Override public void mouseExited(MouseEvent e) { minimizeButton.setIcon(new ImageIcon("minimize.png")); } }); maximizeButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { maximizeButton.setIcon(new ImageIcon("maximize_highlight.png")); } @Override public void mouseExited(MouseEvent e) { maximizeButton.setIcon(new ImageIcon("maximize.png")); } }); closeButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { closeButton.setIcon(new ImageIcon("close_highlight.png")); } @Override public void mouseExited(MouseEvent e) { closeButton.setIcon(new ImageIcon("close.png")); } }); // 将按钮添加到标题栏 titleBarPanel.add(minimizeButton); titleBarPanel.add(maximizeButton); titleBarPanel.add(closeButton); // 将标题栏添加到窗口 this.add(titleBarPanel, BorderLayout.NORTH); // 设置窗口关闭操作 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new CustomWindow(); } }); } } ``` 这样,`origin`变量就能在窗口移动的方法中正确地使用了。希望这次能帮到你!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值