梯形布局

这是一个关于自定义Android视图的博客,作者通过创建`MyView`类继承`ViewGroup`,实现了梯形布局的效果。代码中包含了对子视图的测量和布局,特别是在`onMeasure`和`onLayout`方法中处理了子视图的位置和大小。此外,博客还涉及到网络请求的`OkHttpManager`类,用于处理JSON数据。
摘要由CSDN通过智能技术生成
package com.example.myapplication;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_add;
    private int i = 0;
    private MyView myView;
    private TextView textView;
    private Button btn_del;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        myView = findViewById( R.id.avs );
        btn_add =  findViewById(R.id.btn_add);
        btn_add.setOnClickListener(this);
        btn_del = findViewById( R.id.btn_del );
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add:
                i++;
                textView = new TextView(MainActivity.this);
                textView.setText("这是第"+i+"个");
                textView.setWidth(200);
                textView.setHeight(55);
                if (i%3 ==1){
                    textView.setBackgroundColor(Color.RED);
                }else if (i%3 ==2){
                    textView.setBackgroundColor( Color.GREEN);
                }else {
                    textView.setBackgroundColor(Color.BLUE);
                }
                textView.setOnClickListener( new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent( MainActivity.this, Main2Activity.class );
                        startActivity( intent );
                    }
                } );
                myView.addView( textView );
                break;
            case R.id.btn_del:
                if (i>0){
                i--;
                myView.removeView( textView );
                break;
        }
    }
    }

}



package com.example.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * data;2018/5/30
 * author:任志军
 */

public class MyView extends ViewGroup {
    public MyView(Context context) {
        super( context );
    }

    public MyView(Context context, AttributeSet attrs) {
        super( context, attrs );
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super( context, attrs, defStyleAttr );
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw( canvas );
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure( widthMeasureSpec, heightMeasureSpec );
        measureChildren( widthMeasureSpec,heightMeasureSpec );
        int childCount = getChildCount();
        //定义一个临时高度
        int startHeight=0;
        int startWidth=0;

        for (int a = 0; a <childCount ; a++) {
            View childAt = getChildAt( a );
            childAt.layout( startWidth,startHeight,startWidth+childAt.getMeasuredWidth(),startHeight+childAt.getMeasuredHeight() );
            startHeight+=childAt.getMeasuredHeight();
            if ((a+1)%3==0){
                startWidth=2;
            }else {
                startWidth+=childAt.getMeasuredWidth();
            }
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

    }
}


package com.example.myapplication;




public class Main2Activity extends AppCompatActivity {
private String path="http://365jia.cn/news/api3/365jia/news/headline?page=1";
    private XRecyclerView recyclerView;
private OkHttpManager mokHttpManager=new OkHttpManager();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main2 );
        recyclerView = findViewById( R.id.xlv );
        mokHttpManager.asyncJsonObjectByURL( path, new OkHttpManager.Func3() {
            @Override
            public void onResponse(JSONObject jsonObject) {

            }
        } );
        mokHttpManager.asyncJsonStringByURL( path, new OkHttpManager.Func1() {
            @Override
            public void onResponse(String result) {
                Gson gson = new Gson();
                ReaBean1 reaBean1 = gson.fromJson( result, ReaBean1.class );
                List<ReaBean1.DataBeanX.DataBean> data = reaBean1.getData().getData();

            }
        } );
    }


}


package com.example.myapplication.view;



public class MyRecyterviewAdapter {
}


package com.example.myapplication.uitl;

import android.os.Handler;


public class OkHttpManager {


    private final OkHttpClient mclient;
    private static Handler handler;
    private volatile static OkHttpManager sManager;//防止多个线程同时访问

    public OkHttpManager() {
        mclient = new OkHttpClient();
        handler = new Handler();
    }

    //    使用单例模式,通过获取的方式拿到对象
    public static OkHttpManager getInstance() {
        OkHttpManager instance = null;
        if (sManager == null) {
            synchronized (OkHttpManager.class) {
                if (instance == null) {
                    instance = new OkHttpManager();
                    sManager = instance;
                }
            }
        }
        return instance;
    }
    //    定义要调用的接口
   public interface  Func1{
        void  onResponse(String result);
    }
    interface Func2{
        void onResponse(byte [] result);
    }
  public   interface Func3{
        void  onResponse(JSONObject jsonObject);
    }
//    使编写的代码运行在主线程
//    处理请求网络成功的方法,返回的结果是Json串
private static void onSuccessJsonStringMethod(final String jsonValue, final Func1 callBack){
    handler.post(new Runnable() {
        @Override
        public void run() {
            if (callBack!=null){
                try {
                    callBack.onResponse(jsonValue);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
    });
}
    /**
     * 返回响应的结果是Json对象
     * @param jsonValue
     * @param callBack
     */
    private void onSuccessJsonObjectMethod(final String jsonValue, final Func3 callBack){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack!=null){
                    try{
                        callBack.onResponse(new JSONObject(jsonValue));
                    }catch(JSONException e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    public  void  asyncJsonStringByURL(String url,final Func1 callBack){
        final  Request request = new Request.Builder().url(url).build();
        mclient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
            }
            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if (response!=null&&response.isSuccessful()){
                    onSuccessJsonStringMethod(response.body().string(),callBack);
                }
            }
        });
    }




    /**
     * 请求返回的是json对象
     *
     * @param url
     * @param callBack
     */
    public void asyncJsonObjectByURL(String url, final Func3 callBack) {
        final Request request = new Request.Builder().url(url).build();
        mclient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
            }
            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    onSuccessJsonObjectMethod(response.body().string(), callBack);
                }
            }
        });
    }

}



package com.example.myapplication.uitl;

import android.os.Handler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * data;2018/5/30
 * author:任志军
 */

public class OkHttpManager {


    private final OkHttpClient mclient;
    private static Handler handler;
    private volatile static OkHttpManager sManager;//防止多个线程同时访问

    public OkHttpManager() {
        mclient = new OkHttpClient();
        handler = new Handler();
    }

    //    使用单例模式,通过获取的方式拿到对象
    public static OkHttpManager getInstance() {
        OkHttpManager instance = null;
        if (sManager == null) {
            synchronized (OkHttpManager.class) {
                if (instance == null) {
                    instance = new OkHttpManager();
                    sManager = instance;
                }
            }
        }
        return instance;
    }
    //    定义要调用的接口
   public interface  Func1{
        void  onResponse(String result);
    }
    interface Func2{
        void onResponse(byte [] result);
    }
  public   interface Func3{
        void  onResponse(JSONObject jsonObject);
    }
//    使编写的代码运行在主线程
//    处理请求网络成功的方法,返回的结果是Json串
private static void onSuccessJsonStringMethod(final String jsonValue, final Func1 callBack){
    handler.post(new Runnable() {
        @Override
        public void run() {
            if (callBack!=null){
                try {
                    callBack.onResponse(jsonValue);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
    });
}
    /**
     * 返回响应的结果是Json对象
     * @param jsonValue
     * @param callBack
     */
    private void onSuccessJsonObjectMethod(final String jsonValue, final Func3 callBack){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack!=null){
                    try{
                        callBack.onResponse(new JSONObject(jsonValue));
                    }catch(JSONException e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    public  void  asyncJsonStringByURL(String url,final Func1 callBack){
        final  Request request = new Request.Builder().url(url).build();
        mclient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
            }
            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if (response!=null&&response.isSuccessful()){
                    onSuccessJsonStringMethod(response.body().string(),callBack);
                }
            }
        });
    }




    /**
     * 请求返回的是json对象
     *
     * @param url
     * @param callBack
     */
    public void asyncJsonObjectByURL(String url, final Func3 callBack) {
        final Request request = new Request.Builder().url(url).build();
        mclient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
            }
            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    onSuccessJsonObjectMethod(response.body().string(), callBack);
                }
            }
        });
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.myapplication.MainActivity">
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal" >
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="-"
        android:id="@+id/btn_del"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:gravity="center"
        android:text="三色梯"/>
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="+"
        android:id="@+id/btn_add"/>
  </LinearLayout>
  <com.example.myapplication.MyView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/avs"></com.example.myapplication.MyView>

</LinearLayout>


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.example.myapplication.Main2Activity">
<com.jcodecraeer.xrecyclerview.XRecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/xlv"></com.jcodecraeer.xrecyclerview.XRecyclerView>
</android.support.constraint.ConstraintLayout>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值