Android 自动换行添加控件

PS:转载请注明出处,谢谢

最近在项目里面有几个需要根据返回的数据来自动添加控件的地方,在网上找了一些,然后加上自己写的一些,都一起整理完,然后给自己做个备注,啦啦啦啦啦啦~~~~

先贴一张镇楼效果图(效果图不是很清晰,将就看了)

静态的也来一张

PS:里面主要写了三种样式(不够的话可以自己写View替换),这里代码就只展示第一种类型(太多了也展示不了,嘿嘿(关键是我想要分)),贴的代码里面都有注解的,我就不写了~~~~懒。

  1. HorizontalScollTabHost.java自定义功能
/**
 * Created by $USER_NAME on 2018/8/9 0009.
 * author : tomz  email:ibepend@126.com
 * 滑动添加的控件
 */
public class HorizontalScollTabHost extends LinearLayout implements ViewPager.OnPageChangeListener {

    private final static String TAG = "HorizontalScollTabHost";

    private Context mContext;

    private int mBgColor;
    private int mTextSize;

    private List<String> list;
    private List<Fragment> fragmentList;
    private List<TextView> topViews;
    private int count;

    private LinearLayout mMenuLayout;


    private HorizontalScrollView hscrollview;
    private ViewPager viewpager;

    public HorizontalScollTabHost(Context context) {
        this(context, null);
    }

    public HorizontalScollTabHost(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HorizontalScollTabHost(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;

        init(context, attrs);
    }


    /**
     * 初始化自定义属性和view
     *
     * @param context
     * @param attrs
     */
    private void init(Context context, AttributeSet attrs) {

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.HorizontalScollTabhost);

        mBgColor = typedArray.getColor(R.styleable.HorizontalScollTabhost_top_background, 0x20999999);
        mTextSize = (int) typedArray.getDimension(R.styleable.HorizontalScollTabhost_textSize, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
        typedArray.recycle();

        initView();


    }

    /**
     * 初始化view
     */
    private void initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.horizontal_scroll_tabhost, this, true);

        hscrollview = (HorizontalScrollView) view.findViewById(R.id.horizontalScrollView);
        viewpager = (ViewPager) view.findViewById(R.id.viewpager_fragment);
        viewpager.addOnPageChangeListener(this);

        mMenuLayout = (LinearLayout) view.findViewById(R.id.layout_menu);

    }


    /**
     * 供调用者调用,保证数据独立
     *
     * @param list
     * @param fragments
     */
    public void diaplay(List<String> list, List<Fragment> fragments, Handler handler) {
        this.list = list;
        this.count = list.size();
        this.fragmentList = fragments;
        this.mHandler = handler;
        topViews = new ArrayList<>(count);
        drawUi();
    }


    public void diaplay(List<String> list, Handler handler) {
        this.list = list;
        this.count = list.size();
        this.mHandler = handler;
        topViews = new ArrayList<>(count);
        drawUi();
    }

    public void diaplay(List<String> list) {
        this.list = list;
        this.count = list.size();
        topViews = new ArrayList<>(count);
        drawUi();
    }

    /**
     * 绘制页面所有元素
     */
    private void drawUi() {

        drawHorizontal();


    }


    boolean isFalst = false;
    TextView[] textViews;
    int finalI;
    private Bundle bundle;
    private final int SELCT_SUCCESS = 0x00123;
    private Handler mHandler;
    private int typeId = 0;
    private List<Integer> listNum = new ArrayList<Integer>();

    /**
     * 绘制横向滑动菜单
     */
    private void drawHorizontal() {
//        mMenuLayout.setBackgroundColor(mBgColor);
        textViews = new TextView[count];

        for (int i = 0; i < count; i++) {
            final String menu = list.get(i);
            final TextView tv = (TextView) View.inflate(mContext, R.layout.news_top_tv_item, null);
            textViews[i] = tv;
            //这行代码很重要,
            textViews[i].setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
//            textViews[i].setTextSize(15);
            textViews[i].setText(menu + " ");
            textViews[i].setTag(i);
            finalI = i;

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(15, 10, 0, 10);
            tv.setLayoutParams(lp);


            mMenuLayout.addView(tv);

            topViews.add(tv);

        }

        for (int j = 0; j < textViews.length; j++) {
            textViews[j].setTag(textViews);
            textViews[j].setOnClickListener(new LableClickListener());
        }

        //默认设置第一项为选中(news_top_tv_item.xml里面, android:textColor引用 drawable的selector)
        topViews.get(0).setSelected(true);
        textViews[0].setBackgroundResource(R.drawable.shape_border_nor);
        textViews[0].setTextColor(Color.parseColor("#E95D5C"));
    }

    /**
     * 这个是点击返回当前信息
     */
    class LableClickListener implements View.OnClickListener {

        public LableClickListener() {
        }

        @Override
        public void onClick(View v) {
            TextView[] textViews = (TextView[]) v.getTag();
            TextView tv = (TextView) v;
            for (int i = 0; i < textViews.length; i++) {
                //让点击的标签背景变成橙色,字体颜色变为白色
                if (tv.equals(textViews[i])) {
                    textViews[i].setBackgroundResource(R.drawable.shape_border_nor);
                    textViews[i].setTextColor(Color.parseColor("#E95D5C"));
                    Toast.makeText(mContext, tv.getText().toString() + "", Toast.LENGTH_SHORT).show();
                    //传递属性选择后的商品数据
//                    Message message = new Message();
//                    bundle = new Bundle();
//                    bundle.putString("type_name", tv.getText().toString());
//                    message.setData(bundle);
//                    message.what = SELCT_SUCCESS;
//                    mHandler.sendMessage(message);
                } else {
                    //其他标签背景变成白色,字体颜色为黑色
                    textViews[i].setBackgroundResource(R.drawable.shape_border_select);
                    textViews[i].setTextColor(Color.parseColor("#666666"));
                }
            }

            //点击移动到当前fragment
            viewpager.setCurrentItem(finalI);
            //点击让文字居中
            moveItemToCenter(tv);
        }

    }

    /**
     * 移动view对象到中间
     *
     * @param tv
     */
    private void moveItemToCenter(TextView tv) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int[] locations = new int[2];
        tv.getLocationInWindow(locations);
        int rbWidth = tv.getWidth();
        hscrollview.smoothScrollBy((locations[0] + rbWidth / 2 - screenWidth / 2),
                0);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (mMenuLayout != null && mMenuLayout.getChildCount() > 0) {

            for (int i = 0; i < mMenuLayout.getChildCount(); i++) {
                if (i == position) {
                    mMenuLayout.getChildAt(i).setSelected(true);
                } else {
                    mMenuLayout.getChildAt(i).setSelected(false);
                }
            }
        }

        //移动view,水平居中
        moveItemToCenter(topViews.get(position));

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

}

主要的控件生成代码和滑动居中就已经完成了,剩下的就是用法了

  2. MainActivity.java实现功能效果

public class MainActivity extends AppCompatActivity {

    private final static String TAG = "MainActivity";
    private HorizontalScollTabHost tabHost;
    private List<String> mList;
    private String strTiele[] = new String[]{"头条", "推荐", "关注", "视频", "Java SE", "Android", "Html5", "我不喜欢"};
    private static String[] testName = {"日历", "360", "三国", "消除", "播放器",
            "游戏", "清理大师", "跑酷", "壁纸", "单机斗地主",
            "捕鱼达人3", "雷电2014(雷霆版)", "打车", "输入法"};
    private String title;

    //
    private WarpLinearLayout warpLinearLayout;

    private Button btn;

    private AutoLayoutView layoutView;
    private List<AutoData> dataList;
    private String autoName[] = new String[]{"降龙", "黯然", "左右", "七十", "拈花", "蛤蟆", "吸星", "打狗", "醉拳"};
//    String atuoUrl[]=new String[]{""};

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

        tabHost = findViewById(R.id.tabhost);
        mList = new ArrayList<>();
        for (int i = 0; i < strTiele.length; i++) {
            mList.add(strTiele[i]);
        }

        tabHost.diaplay(mList);

        initWarpData();

        initAutoIcon();
    }

    private void initWarpData() {
        btn = (Button) findViewById(R.id.btn);
        warpLinearLayout = (WarpLinearLayout) findViewById(R.id.warpLinearLayout);

        for (int j = 0; j < 11; j++) {
            int n = new Random().nextInt(10) + 5;
            StringBuffer stringBuffer = new StringBuffer();
            Random random = new Random();
            Log.i(TAG, "n=" + n);
            for (int i = 0; i < n; i++) {
                stringBuffer.append((char) (65 + random.nextInt(26)));
                Log.i(TAG, "StringBuffer=" + stringBuffer.toString());
            }
            final TextView tv = new TextView(MainActivity.this);
            tv.setText(stringBuffer.toString() + "000");
            tv.setBackgroundResource(R.drawable.shape_text_border);
            tv.setTextColor(getResources().getColor(R.color.black));
            tv.setPadding(10, 10, 10, 10);
            warpLinearLayout.addView(tv);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, "$ - " + tv.getText().toString() + " - $", Toast.LENGTH_SHORT).show();
                }
            });
        }


        /**
         * 单个添加
         */
        /*
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int n = new Random().nextInt(10) + 5;
                StringBuffer stringBuffer = new StringBuffer();
                Random random = new Random();
                for (int i = 0; i < n; i++) {
                    stringBuffer.append((char) (65 + random.nextInt(26)));
                }
                TextView tv = new TextView(MainActivity.this);
                tv.setText(stringBuffer.toString() + "000");
                tv.setBackgroundResource(R.drawable.shape_text_border);
                tv.setPadding(10, 10, 10, 10);
                warpLinearLayout.addView(tv);
            }
        });*/

    }


    private void initAutoIcon() {
        layoutView = findViewById(R.id.autoView);
        dataList = new ArrayList<AutoData>();
        for (int i = 0; i < autoName.length; i++) {
            AutoData autoData = new AutoData();
            autoData.setName(autoName[i]);
            autoData.setUrl("http://qcloudimg.ichongxin.com/menuicon/qiguantubiao/yimiao.png");
            dataList.add(autoData);
        }

        layoutView.addData(dataList);

        layoutView.setOnFlowLayoutListener(new AutoLayoutView.FlowLayoutListener() {
            @Override
            public void onItemClick(View view, int poition) {
                Toast.makeText(MainActivity.this, "--> " + dataList.get(poition).getName() + " <--", Toast.LENGTH_SHORT).show();
            }
        });
    }


//    private final int SWITCH_PAGE = 0x00123;
//
//    Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case SWITCH_PAGE:
//                    //接收dialog点击以后得返回数据
//                    title = msg.getData().getString("type_name");
//                    Log.i(TAG, "handleMessage: " + title);
//                    break;
//            }
//        }
//    };
}

最后在贴上布局文件activity_main.xml

<?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=".MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:gravity="center|left"
                android:text="滑动控件居中显示"
                android:textColor="#000" />


            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#FFF">

                <com.auto.widget.view.HorizontalScollTabHost
                    android:id="@+id/tabhost"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:layout_marginRight="48dp"
                    android:layout_marginTop="5dp" />

                <ImageView
                    android:id="@+id/mall_more_image"
                    android:layout_width="45dp"
                    android:layout_height="35dp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginBottom="8dp"
                    android:layout_marginTop="8dp"
                    android:src="@mipmap/more" />
            </RelativeLayout>


            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="自动换行显示控件(根据布局或者单个控件来显示)"
                android:textColor="#000" />


            <Button
                android:id="@+id/btn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="add"
                android:textSize="20dp"
                android:visibility="gone" />

            <com.auto.widget.view.WarpLinearLayout
                android:id="@+id/warpLinearLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/btn"
                android:background="#FFF"
                android:padding="10dp"
                app:grivate="left"
                app:horizontal_Space="10dp"
                app:isFull="false"
                app:vertical_Space="10dp"></com.auto.widget.view.WarpLinearLayout>


            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="自动换行显示图标控件(同上)"
                android:textColor="#000" />

            <com.auto.widget.view.AutoLayoutView
                android:id="@+id/autoView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"></com.auto.widget.view.AutoLayoutView>

            <View
                android:layout_width="match_parent"
                android:layout_height="20dp" />
        </LinearLayout>
    </ScrollView>
</RelativeLayout>

第一个功能的全部代码就已经全部贴完了,最后附上下载链接:

CSDN(跪求有分的大佬下载这个,攒点分^_^):https://download.csdn.net/download/wjilikely/10596183

GitHub:https://github.com/wangjiand/AutoLayoutView-master

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值