Android html+动态添加控件,实现textview最后一行的显示效果

效果图:

需求:最后的“详情”是固定要在最后一行的最右侧,并且能被点击

 

1.xml中布局



        

    

2.activity中

  @ViewId(R.id.text)
    TextView text;
    @ViewId(R.id.txtlayout)
    FrameLayout txtlayout;

    private int onGlobalLayout=0;
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final String redStr = "班组隧道工程矿山法开挖";
        txtlayout.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (onGlobalLayout==0){
                    //这个宽度我是取的手机屏幕的宽度,实际应用中请使用控件的宽度
                            float tvWidth = getWindowManager().getDefaultDisplay().getWidth();
                            TextPaint textPaint = MainActivity.this.text.getPaint();
                            float xiangqingWidth = textPaint.measureText("详情>");
                            int paddingleft = Math.round(tvWidth-xiangqingWidth);
                            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                                    FrameLayout.LayoutParams.WRAP_CONTENT , FrameLayout.LayoutParams.WRAP_CONTENT);
                            lp.gravity = Gravity.BOTTOM;
                            lp.setMargins(paddingleft-25, 0, 0, 0);
                            TextView tv = new TextView(MainActivity.this);
                            tv.setGravity(Gravity.CENTER);
                            tv.setLayoutParams(lp);
                            tv.setText("详情>");
                            tv.setTextColor(Color.GRAY);
                            tv.setTextSize(14);
                            txtlayout.addView(tv);
                            tv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Toast.makeText(MainActivity.this,"点击了详情",Toast.LENGTH_SHORT).show();
                                }
                            });
                            MainActivity.this.text.setText(Html.fromHtml("您发布的寻找" + "" + redStr + "" + "类型信息找到符合您要求的供应方了,赶快来看看吧!"));
                            onGlobalLayout++;
                        }

                    }

                });
    }

 

你可能感兴趣的:(Android,开发)